Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckedListBox DataSource suddenly not working

Tags:

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.

like image 628
roxhens Avatar asked Oct 18 '16 10:10

roxhens


1 Answers

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";
like image 74
Stef Geysels Avatar answered Sep 22 '22 16:09

Stef Geysels