如何根据数据库中的文本更改C#中的按钮文本?

时间:2015-12-03 14:45:28

标签: c#

我是c#的新手,我使用的是Windows窗体。

screenshot

如屏幕截图所示,我想在form1加载所有按钮时使用'文本根据其在数据库上的名称进行更改。 我已经编写了一些从数据库导入数据的代码,但接下来我想在form1加载时根据数据库中的名称更改每个按钮文本。

请帮助我如何修改此代码以实现我想要的效果。谢谢

private void Form1_Load(object sender, EventArgs e)

    {
        SqlConnection con = new SqlConnection("Data Source=PCNDVR-TOSH!;Initial Catalog=mydb;Integrated Security=True");

        con.Open();
        SqlCommand cm = new SqlCommand("SELECT * FROM button_txt");

        cm.Connection = con;

        SqlDataAdapter da = new SqlDataAdapter(cm);
        DataTable dt = new DataTable();
        da.Fill(dt);
        con.Close();


    }

2 个答案:

答案 0 :(得分:2)

这样的东西?

foreach (DataRow row in dt.Rows)
{
    Button targetButton = null;

    switch(row["button_name"].ToString().ToLower())
    {
        case "button1":
            targetButton = myFirstButton;
            break; 
        case "button2":
            targetButton = mySecondButton;
            break; 
        case "button3":
            targetButton = myThirdButton;
            break; 
    }

    targetButton.Text = row["button_txt"].ToString();
}

答案 1 :(得分:1)

//After the connection is closed
DataRow[] dra = dt.Select("button_name = 'button1'");
myFirstButton.Text = dra[0]["button_txt"];

//Alternate way of referencing datarow 
dra = dt.Select("button_name = 'button2'");
mySecondButton.Text = dra[0][1];entries

//Removing the need for the dra[]
myThirdButton.Text = dt.Select("button_name = 'button3'")[0][1];