我通过使用列中的SqlCommand
和SqlReader
并将其存储在List<String>
中并添加到 ComboBox(类型:DropDownList)来重新获取值,但事件很快我已经从数据库中删除了一些这样的值,Combobox仍在显示它。
我正在通过
清除分配项目mycombobox.Items.Clear();
看起来它不会受到每次表单加载时重试的值的影响。
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection=new List<string>();
// Open connection to the database
string ConnectionString = @"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
foreach(string pname in namesCollection)
cb.Items.Add(pname);
namesCollection.Clear();
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
提前致谢。
答案 0 :(得分:1)
答案 1 :(得分:0)
让我们说填充ComboBox
的代码放在populate_cb()
方法
private void populate_cb(){
cb.Items.Clear();
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
// Open connection to the database
string ConnectionString = @"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
cb.Items.Add("Select");
while(rdr1.Read())
{
cb.Items.Add(rdr1[0].ToString());
}
cb.SelectedIndex =0;
con1.Close();
}
catch(Exception ex){
// handle exception
}
}//end of populate_cb()
致电populate_cb()
方法表单form_load()
和
在删除过程 之后从地方拨打电话
您需要确保删除过程确实删除了数据库中的记录!