簡體   English   中英

基於 SQL 列動態創建按鈕

[英]Dynamically Create Buttons based off of SQL Column

我正在嘗試編寫一段代碼,從我的 SQL 列中提取並為該列中的每個值創建一個按鈕。 例如,如果我的 A 列包含“測試 1”、“測試 2”和“測試 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);
            }

        }

更新正如評論中提到的,我無法命名我的按鈕,所以我添加了 function 。至於為什么我只看到一個按鈕,我假設這是因為所有按鈕都是在頂部創建的彼此顯示,而不是顯示在行或列中。

你需要在這里做一些事情。

首先查看表中的記錄,真的有3條記錄嗎? 因為根據您的代碼,它應該適用於 3 個按鈕。

其次,您沒有設置按鈕的文本。

在初始化它時using SqlConnectionSqlCommand對象。

並請在某些配置文件中定義您的連接字符串。

為了解決我面臨的問題,最終是沒有文本的按鈕並且全部顯示在彼此之上,我添加了一個 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);
            }

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM