C# 使用读卡器将组合框与默认文本绑定
我有一个组合框,用于填充来自数据库的数据。我想要像这样的默认文本 “请选择”将在您第一次加载页面时出现在组合框上,并且在您重置页面时,它必须位于顶部。仅打开组合框时,将显示默认文本。请帮忙 下面是我如何绑定我的组合框C# 使用读卡器将组合框与默认文本绑定,c#,winforms,combobox,C#,Winforms,Combobox,我有一个组合框,用于填充来自数据库的数据。我想要像这样的默认文本 “请选择”将在您第一次加载页面时出现在组合框上,并且在您重置页面时,它必须位于顶部。仅打开组合框时,将显示默认文本。请帮忙 下面是我如何绑定我的组合框 private void LoadCombo() { try { oConnection = new SqlConnection(_connectionString); oCommand
private void LoadCombo()
{
try
{
oConnection = new SqlConnection(_connectionString);
oCommand = new SqlCommand("select * from tbldpt", oConnection);
oAdapter = new SqlDataAdapter(oCommand);
oConnection.Open();
oDataset = new System.Data.DataSet();
SqlDataReader oReader = oCommand.ExecuteReader();
while (oReader.Read())
{
string _Combobox = oReader["Name"].ToString();
cboDepartment.Items.Add(_Combobox);
}
cboDepartment.Items.Insert(0, "--Select Department--");
oReader.Close();
oConnection.Close();
}
catch(Exception ex)
{
}
}
试试这个片段
cboDepartment.Items.Add("--Select Department--");
while (oReader.Read())
{
string _Combobox = oReader["Name"].ToString();
cboDepartment.Items.Add(_Combobox);
}
cboDepartment.selectedIndex=0;
创建字符串列表并与组合框绑定
try
{
oConnection = new SqlConnection(_connectionString);
oCommand = new SqlCommand("select * from tbldpt", oConnection);
oConnection.Open();
oDataset = new System.Data.DataSet();
SqlDataReader oReader = oCommand.ExecuteReader();
list<string> _combobox=new list<string>();
_combobox.add("--Select Department--");
while (oReader.Read())
{
_combobox.Add(oReader["Name"].ToString());
}
cboDepartment.Datasource=_combobox
oReader.Close();
oConnection.Close();
}
catch(Exception ex)
{
}
试试看
{
oConnection=新的SqlConnection(_connectionString);
oCommand=newsqlcommand(“从tbldpt中选择*”,occonnection);
oConnection.Open();
oDataset=new System.Data.DataSet();
SqlDataReader或Reader=oCommand.ExecuteReader();
列表_combobox=新列表();
_combobox.add(“--选择部门--”);
while(oReader.Read())
{
_添加(oReader[“Name”].ToString());
}
cboDepartment.Datasource=\u组合框
oReader.Close();
o连接。关闭();
}
捕获(例外情况除外)
{
}
LoadCombo方法的调用方式/调用位置?public UserList(){LoadCombo();}插入默认文本后,只需调用cboDepartment.SelectedIndex=0;谢谢,它按照我想要的方式工作。最后一件事,你知道为什么我在尝试将int转换为string时会出现这个错误吗;这是我的代码行。。。错误:“输入的格式不正确”int userid=int.Parse(i.SubItems[3].Text);用于绑定4项时的listview控件