Question

I made a datagridview and I need to pass my datagridview data to a SQL Server database. For that I have created all the codes and after a button click I want to pass those value so I made a code following but it is giving me an error that this does not contain a definition for .Text and no extension method for text. It is giving me an error line under .Text so what is the correct extension method for text.

private void button1_Click(object sender, EventArgs e)
{
   // Adding Values to Data Base
   string mySQL = "INSERT INTO Employee_login VALUES ("
     + Convert.ToInt32(dataGridView1.Rows[RowCount - 1].Cells[0].Text.Trim()) + ", '"
     + dataGridView1.Rows[RowCount - 1].Cells[1].Text.Trim() + "','";
}
Was it helpful?

Solution

You need to be calling the .Value property on your dataGridView1, not the .Text property.

Something like this:

private void button1_Click(object sender, EventArgs e)
{
  // Adding Values to Data Base
  string mySQL = "INSERT INTO Employee_login VALUES ("
   + Convert.ToInt32(dataGridView1.Rows[RowCount - 1].Cells[0].Value) + ", '"
   + dataGridView1.Rows[RowCount - 1].Cells[1].Value + "','";
}

You didn't mention in your post however, if you actually need to call the .Trim() method; which will not work in this case using .Value.

OTHER TIPS

Try using this to databind. You will not have to manually enter values into the database if so.

SqlConnection conn = new SqlConnection(@"Your connection string");
DataTable dt = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from Employee_login", conn);
dataGridView1.DataSource = dt; 
dataAdapter.Fill(dt);

On the button click event you can provide something like

dataAdapter.Update(dt)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top