如何在运行时将当前项添加到组合框中 [英] How to add the current items into combobox at runtime

查看:74
本文介绍了如何在运行时将当前项添加到组合框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单中我有连接到sql server的组合框,组合框中的项目是标识,两个文本框和日期时间选择器和按钮添加,当我按下按钮添加在运行时我想看到组合框中当前添加信息的数量,如果你有任何帮助,请回答我。



非常感谢。

In my forms I have combobox linked to sql server, the items in combobox is identity, two textbox and datetimepickers and button add ,when I press the button add at runtime i want to see the numbers of current adding information in combobox, please if you have any help answer me.

Thanks a lot.

推荐答案

这个:

This:
//the problems is inside loop
if (comboBox1.SelectedIndex != 0)
{
  this.comboBox1.Items.Add(this.comboBox1.SelectedIndex);
}



不是循环。这是一个if-Statement。如果if-Statement的谓词评估为真,那么if-Statement块中的代码将被执行一次



我假设你想在任何情况下将新创建的记录作为组合框项插入,对吧?那你就不需要if语句了。目前,如果当前选择任何项目,您只会插入新的组合框项目。目前您实际上插入了组合框的SelectedIndex - 您可以轻松地从代码中读取。这没有多大意义。我想你会想要这样的东西:




is not a loop. It's an if-Statement. The code in the block of the if-Statement gets executed once if the predicate of the if-Statement evaluates to true.

I assume you want to insert the newly created record as a combobox-item in any case, right? Then you won't need an if-Statement. Currently you only would insert the new combobox-item if there's any item currently selected. And currently you actually insert the SelectedIndex of the combobox - as you can easily read from your code. That doesn't make much sense. I assume you would want something like this:

//no if-Statement here
comboBox1.Items.Add(String.Concat(textBox1.Text, " ,", dateTimePicker1.Text, " ,", textBox3.Text));





然后那里您的代码还有其他一些问题:

- 使用SQL参数。 这里的简单示例 [ ^ ]

- 如果发生异常,则报告它然后继续进行,好像什么也没发生。你应该做一些事情来处理错误,除了报告它。

- 如果抛出异常,你的连接将不会被关闭。



edits:拼写错误



And then there are a couple of other problems with your code:
- Use SQL-Parameters. Simple example here[^]
- If an exception occurs you report it and then keep going as if nothing happened. You should do something to handle the error besides reporting it.
- Your connection won't get closed in case of an exception being thrown.

edits: typos


这篇关于如何在运行时将当前项添加到组合框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆