如何将动态按钮添加到列表视图?

时间:2014-04-30 07:19:30

标签: winforms listview c#-4.0

我有一个表单和一个ListView控件我尝试使用此代码动态添加按钮

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;
}

示例表有3条记录,但它只显示listview中的1个按钮,该按钮是示例表的第一条记录的名称。在调试期间,它进入while循环3次?请指导我做的错误是什么?

2 个答案:

答案 0 :(得分:1)

列表框不支持添加控件。它可能是在窗体上的相同位置绘制所有按钮,这就是您没有看到它们的原因。解决这个问题的更好方法是使用flowLayoutPanel代替控件。

答案 1 :(得分:0)

以上代码在我的系统中运行如下:enter image description here