The listbox does not support well adding controls. It probably is drawing all the buttons in the same location on the form and that is why you do not see them. A better way to go around this would be to use a flowLayoutPanel to contain your controls instead.
how to add dynamically buttons to a listview?
Question
I have a form and a ListView Control in it I'm trying to add buttons to it dynamically using this code
SqlDataReader reader = null;
SqlConnection test = new SqlConnection(@"Data Source=localhost;Initial Catalog=demo;Integrated Security=True;Pooling=False");
string query = "SELECT* FROM Sample";
try
{
test.Open();
SqlCommand cmd = new SqlCommand(query, test);
reader = cmd.ExecuteReader();
while (reader.Read())
{
int btnID = Convert.ToInt32(reader["Id"]);
string btnName = reader["name"].ToString();
Button btnObj = new Button();
btnObj.Name = btnID.ToString();
btnObj.Text = btnName;
new System.Drawing.Size(150, 30);
this.listView1.Controls.Add(btnObj);
}
}
catch (Exception)
{
throw;
}
The sample table has 3 records but it shows only 1 button in the listview that was the name of first record of the sample table. During debug it enters in the while loop 3 times? Kindly guide me what was the mistake i'm doing?
Solution
OTHER TIPS
Above codes are working in my system like below:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow