I have a CheckedListBox that used this code to get the items.
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");
}
}
}
Suddenly, it doesn't work anymore and gives the following error:
Exception thrown: 'System.NullReferenceException' in System.Windows.Forms.dll
What can I do to fix this, or is there any other way how to bind a CheckedListBox to a DataTable? Thanks in advance.
I don't think I'll provide an answer, but I would help you improve some of the code-lines.
Getting a string from an array, seperated with any seperator:
string list = string.Join(",", kv);
If a string will become a bit messed-up with al the +
operators:
string query = string.Format("SELECT {0} FROM [dbo].[{1}]", list, tableName);
// Or
string query = $"SELECT {list} FROM [dbo].[{tableName}]"
To improve speed and performance, try to cast only once:
var clb = (CheckedListBox)clk;
clb.DataSource = ds.Tables[0];
clb.DisplayMember = "Description";
clb.ValueMember = "Id";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With