MAC
MAC

Reputation: 6577

Display data on a text box

i have one database, and it contains some columns. My requirement is that how to display each of the data that i stored in the databse on a text box? my code is shown below (after the connection string)

conn.Open();
mycommnd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(mycommnd);
DataTable dt = new DataTable();
da.Fill(dt);

What changes that i make after da.Fill(dt) for displaying data on the text box.

Upvotes: 2

Views: 13003

Answers (4)

hadi teo
hadi teo

Reputation: 936

You need to loop inside each columns in the DataTable to get the values and then concatenate them into a string and assign it to a textbox.Text property

        DataTable dt = new DataTable();
        TextBox ResultTextBox;

        StringBuilder result = new StringBuilder();

        foreach(DataRow dr in dt.Rows)
        {
            foreach(DataColumn dc in dt.Columns)
            {
                result.Append(dr[dc].ToString());
            }
        }

        ResultTextBox.Text = result.ToString();

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

The DataTable consists of rows and columns, that you can reach in some different ways:

// get value from first row, first column
myTextBox.Text = dt.Rows[0][0]; 
// get value from first row, column named "First",
myTextBox.Text = dt.Rows[0]["First"]; 

Upvotes: 0

Aamir
Aamir

Reputation: 15576

Something like:

textBox1.Text = dt.Rows[0].ItemArray[0].ToString();

Depends on the name of your textbox and which value you want to put into that text box.

Upvotes: 3

Aragorn
Aragorn

Reputation: 839

One form of using the ExecuteScalar:

textBox.Text = mycommnd.ExecuteScalar().ToString();

Upvotes: 0

Related Questions