W
W
White_Bambie2020-06-18 13:01:32
MySQL
White_Bambie, 2020-06-18 13:01:32

How to get Checkedlistbox value from MySQL database?

There is a Checkedlistbox on the form. The user selects items from the list and the data is loaded into the database.

if (cl_Additional.CheckedItems.Count > 0)
{
  for (int i = 0; i < cl_Additional.CheckedItems.Count; i++)
  {
    if (additional == "")
    {
      additional = cl_Additional.CheckedItems[i].ToString();                   
    }
    else
    {
    additional += ", " + cl_Additional.CheckedItems[i].ToString();
    }
  }
}
MySqlConnection con = new MySqlConnection(AppSetting.ConnectonString());

con.Open();

MySqlCommand cmd;
cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO patients(Additional) VALUES(@Additional)";
cmd.Parameters.AddWithValue("@Additional", additional);

cmd.ExecuteNonQuery();
con.Close();


How to fetch data from db and add it to Checkedlistbox[cl_Additional]?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
White_Bambie, 2020-06-20
@White_Bambie

Did it like this:

MySqlConnection con = new MySqlConnection(AppSetting.ConnectonString());
            MySqlCommand cmd;
            cmd = con.CreateCommand();
            cmd.CommandText = "SELECT * FROM patients WHERE id='"+ MyListBox.SelectedValue + "';";

            try
            {
                con.Open();

                MySqlDataReader sdr = cmd.ExecuteReader();
                
                string[] sAdditional = new string[] { };
                char[] mychars = { ',' };

                // Чистим чекбоксы
                while (cl_Additional.CheckedItems.Count > 0)
                {
                    cl_Additional.SetItemChecked(cl_Additional.CheckedIndices[0], false);
                }

                // Загружаем данные
                while (sdr.Read())
                {           
                    sAdditional = sdr.GetString("Additional").Split(mychars);
                }

                // Заполняем список чекбоксов
                int length = sAdditional.Length;
                for (int i = 0; i < length - 1; i++)
                {
                    string fetr = sAdditional[i];
                    for (int j = 0; j <= cl_Additional.Items.Count - 1; j++)
                    {
                        if (cl_Additional.Items[j].ToString() == sAdditional[i])
                        {
                            cl_Additional.SetItemChecked(j, true);
                            break;
                        }
                    }
                }

                con.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Подключение к серверу отсутствует");
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question