c# - 从数据库中获取值并分配按钮文本

标签 c#

我有一个部门表,有 5 行。我有一个选择命令,它从部门表中单独获取 dept_name 列。我想将这些值 (row["Dept_Name"].tostring()) 一个一个分配给每个按钮。 例如:如果我的输出是 部门1 部门2 部门3 部门4 部门5

我想将按钮的文本值(设计中已有 5 个按钮)指定为 button1.text = "dept1"; button2.text = "dept2"; button3.text = "dept3";等等。

我如何实现它。 我使用了以下代码。

           MySqlConnection con = new MySqlConnection(myconnectionstring);
        string getdept = "SELECT DEPT_NAME FROM DEPTARTMENT";
        con.Open();
        MySqlCommand cmd = new MySqlCommand(getdept,con);
        MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        foreach (DataRow Row in dt.Rows)
        {

            Button1.Text = Row["DEPT_NAME"].ToString();
       /* i am stuck at this part on how to each row to a separte button text.*/

        }

最佳答案

无需迭代:

Button1.Text = dt.Rows[0]["DEPT_NAME"].ToString();
Button2.Text = dt.Rows[1]["DEPT_NAME"].ToString();
Button3.Text = dt.Rows[2]["DEPT_NAME"].ToString();
Button4.Text = dt.Rows[3]["DEPT_NAME"].ToString();
Button5.Text = dt.Rows[4]["DEPT_NAME"].ToString();

关于c# - 从数据库中获取值并分配按钮文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28630681/

相关文章:

c# - 如何从 .NET 中的 javascript 获取结果

c# - 为什么我们不能从实例对象访问静态成员?

c# - AspNet Identity - 重复外键的自定义 IdentityRoleClaim 和 IdentityUserRole 和 IdentityUserClaim

c# - 使用带反射的 XPath 样式查询

c# - 带有 ASP.NET Core 的 Azure AD B2C - 无法编辑配置文件

c# - Visio - 检查形状是否已连接

c# - 使用 WinAppDriver,我需要有关如何在 WPF 应用程序中打开新窗口时更改焦点的帮助

c# - 如何解析两个元素之间的单词并将其提取出来

c# - 根据文本长度调整文本框和表单大小

c# - 带有消息队列的发布订阅者模型库