Ameena
Ameena

Reputation: 187

To get values from db and assign button text

I have a deptarment table and have 5 rows. I have a select command which gets dept_name column alone from the department table. I want to assign these values (row["Dept_Name"].tostring()) to each button one by one. ex: if my output is dept1 dept2 dept3 dept4 dept5

I want to assign text value of buttons (5 buttons already in design) as button1.text = "dept1"; button2.text = "dept2"; button3.text = "dept3"; and so on.

How do i achieve it. I used the following code.

           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.*/

        }

Upvotes: 1

Views: 307

Answers (3)

hnafar
hnafar

Reputation: 611

see this post, you can do

var i = 0;
foreach (DataRow Row in dt.Rows)
{
    i++;
    var button = Page.GetControl("Button" + i) as Button;
    button.Text = Row["DEPT_NAME"].ToString();
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could use a for-loop and Controls.Find:

for(int i = 0; i < dt.Rows.Count; i++)
{
    string buttonName = "Button" + i.ToString();
    Control[] buttons = this.Controls.Find(buttonName, false);
    if(buttons.Length == 1 && buttons[0] is Button)
    {
        Button btn = (Button) buttons[0];
        btn.Text = dt.Rows[i].Field<string>("DEPT_NAME");
    }
    else throw new Exception("Something went wrong!");
}

Upvotes: 1

fubo
fubo

Reputation: 45947

no need to iterate:

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();

Upvotes: 2

Related Questions