buddy
buddy

Reputation: 428

how to add dynamically buttons to a listview?

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?

Upvotes: 0

Views: 82

Answers (2)

Kumar Manish
Kumar Manish

Reputation: 3772

Above codes are working in my system like below:enter image description here

Upvotes: 0

Dimitris Kalaitzis
Dimitris Kalaitzis

Reputation: 1426

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.

Upvotes: 1

Related Questions