1

Lets say I have a table named Table_T in the SQL database and it contains 6 columns (column1, column2, ..., column6).

The following code populates all columns from the database into dataGridView:

private void button1_Click(object sender, EventArgs e)
{

    SqlConnection cn = new SqlConnection(
        "Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
    cn.Open();
    SqlCommand cm = new SqlCommand("SELECT *FROM Table_T");
    cm.Connection = cn;

    SqlDataAdapter da = new SqlDataAdapter(cm);
    DataTable dt = new DataTable();
    da.Fill(dt);
    cn.Close();
    dataGridView1.DataSource = dt;
}

But how can I only select column3 & column5 and populate them into dataGridview1?

1
  • SqlCommand cm = new SqlCommand("SELECT column3,column5 FROM Table_T"); Commented Nov 1, 2015 at 21:54

3 Answers 3

3
SELECT column3, column5 FROM Table_T

Why wouldn't that work?

Sign up to request clarification or add additional context in comments.

2 Comments

@naouf great! Please mark it as the correct answer by pressing the tick next to the answer :)
@naouf When a post answers your question, you can kindly click check mark near the answer to make it accepted. This way it will be more helpful for users in future. While you can only mark one answer as accepted, but when you reached 15 reputation scores, you can vote up as many answer as you find helpful, including the accepted one. Also you can vote for good questions. :)
1

if you dont need everything back from the table you should use

select col1, col2 from table 

and if you need conditions on it use your where clause

However if do need to grab all th data but display only certain information at certain times I would use a foreach loop like so

foreach(var item in dt.Rows)
{
  var colValue0 = item[0].ToString()
  var colValue1 = item[1].ToString()
  var colValue2 = Convert.ToIn16(item[2])
}

---- edit ----

relooking at your question, if you were binding this to a gridview and only wanted certain information you should add these values to a new datatable then display only the new datatable

so you would need to do something like

var bindableDt = new Datatable();
bindableDt.Columns.Add("colName1")
bindableDt.Columns.Add("colName2")

foreach(var item in dt.Rows)
{
    bindableDt.Row.Add(dt.Rows[0], dt.Rows[1]);
}
gridview.Datasource = bindableDt;

Comments

0

[This answer was initially posted as comment by @capricorn]

SqlCommand cm = new SqlCommand("SELECT column3,column5 FROM Table_T")

this code worked very well. thank you all for your help . all respect and regards.

1 Comment

Since there is a post that answers your question, you can delete this post and accept this answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.