winforms 基于SQL列动态创建按钮

qoefvg9y  于 2022-11-30  发布在  其他
关注(0)|答案(2)|浏览(151)

我正在尝试编写一段代码,从我的SQL列中提取并为该列中的每个值创建一个按钮。例如,如果我的列A包含“test 1”、“test 2”和“test 3”,则代码应生成三个按钮,其中也包含该值的文本。

以下是我到目前为止所尝试的。这段代码只给了我一个按钮,而且是空白的。

private void button7_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(@"connstring");
            string strsql;
            strsql = "SELECT buttonID from table1 ";
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataReader reader = null;
            cmd.Connection.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {           
                Button newButton = new Button();
                newButton.Text = reader["buttonID"].ToString();
                newButton.Location = new Point(1, 10);
                newButton.Size = new Size(100, 50);
                this.Controls.Add(newButton);
            }

        }

UPDATE正如在注解中提到的,我无法命名按钮,所以我在中添加了该函数。至于为什么我只看到一个按钮,我假设这是因为所有按钮都是在彼此的顶部创建的,而不是按行或列显示。

1dkrff03

1dkrff031#

你需要在这里做一些事情。
首先,检查表中的记录,你真的有3条记录吗?因为根据你的代码,它应该为3个按钮工作。
第二,您没有设置按钮的文本。
在初始化using时,将其与SqlConnectionSqlCommand对象一起使用。
请在某个配置文件中定义连接字符串。

clj7thdc

clj7thdc2#

为了解决我所面临的问题,最终是按钮没有文本,所有显示在彼此的顶部,我添加了一个FlowLayoutPanel,并将按钮(控件)添加到中。感谢前面的答案帮助我解决了这个问题。

private void button7_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(@"connstring");
            string strsql;
            strsql = "SELECT buttonID from table1 ";
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataReader reader = null;
            cmd.Connection.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {           
                Button newButton = new Button();
                newButton.Text = reader["buttonID"].ToString();
                newButton.Size = new Size(100, 50);
                this.Controls.Add(newButton);
                flowLayoutPanel1.Controls.Add(newButton);
            }

        }

相关问题