且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时将当前项添加到组合框中

更新时间:2023-12-06 15:32:22

这个:

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