我有一个使用此代码获取项目的 CheckedListBox。
public static void GetDisplayValueList(object clk, string[] kv, string tableName)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
string list = "";
foreach (string item in kv)
list += item + ",";
string query = "SELECT " + list.Substring(0, list.Length - 1) + " FROM [dbo].[" + tableName + "]";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
((CheckedListBox)clk).DataSource = ds.Tables[0];
((CheckedListBox)clk).DisplayMember = "Description";
((CheckedListBox)clk).ValueMember = "Id";
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred: " + ex.Message, "Error");
}
}
}
突然,它不再工作并给出以下错误:
Exception thrown: 'System.NullReferenceException' in System.Windows.Forms.dll
我该怎么做才能解决这个问题,或者有没有其他方法可以将 CheckedListBox 绑定(bind)到 DataTable? 提前致谢。
最佳答案
我不认为我会提供答案,但我会帮助您改进一些代码行。
从数组中获取字符串,用任何分隔符分隔:
string list = string.Join(",", kv);
如果一个字符串在所有 +
运算符的作用下变得有点困惑:
string query = string.Format("SELECT {0} FROM [dbo].[{1}]", list, tableName);
// Or
string query = $"SELECT {list} FROM [dbo].[{tableName}]"
为了提高速度和性能,尝试只施放一次:
var clb = (CheckedListBox)clk;
clb.DataSource = ds.Tables[0];
clb.DisplayMember = "Description";
clb.ValueMember = "Id";
关于c# - CheckedListBox 数据源突然不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40105779/