Reputation: 985
I recently write a simple program that use database.
I've created an DB1.MDF and get data from it.
When I try to do Select from its Table (i.e. Table1), it gets run time error!
How I should do that?!
One more question:
I've created Data Grid View and put data in that. Now, how I can for example use column[2] of it (e.g. column[2] in my dataGridView is LastName and I want to save all LastNames in one String).
Here is my Code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\DB1.mdf;
Integrated Security=True;User Instance=True";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT ID, Name, LastName from Table1 WHERE Name == Joe ";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = dataGridView1.Columns[0].ToString();
}
Upvotes: 0
Views: 187
Reputation: 108937
The select query should be like this
cmd.CommandText = "SELECT ID, Name, LastName from Table1 WHERE Name = 'Joe'";
And for your second question, you could use something like this
private void button2_Click(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
dataGirdView1.Rows.Cast<DataGridViewRow>().ToList()
.ForEach(r => builder.Append(r.Cells[2].Value));
textBox1.Text = builder.ToString();
}
Upvotes: 3
Reputation: 7613
This query seems wrong.
SELECT ID, Name, LastName from Table1 WHERE Name == Joe
Can you try this?
cmd.CommandText = "SELECT ID, Name, LastName from Table1 WHERE Name = 'Joe'"
Also, please post the details of the error message.
Upvotes: 0
Reputation: 583
Bala R has it right, the == operator does not exist in SQL, therefore if your testing for an equality you should use the single = operator. And if you're comparing strings (varchar or nvarchar in SQL) you should put them in single quotes i.e. 'Joe'.
Upvotes: 0