1

I have a Richtextbox where user will update the data in a SQL database. The updated data will then be shown in a datagridview. However, the updated value will have a system.windows.forms.richtextbox.text: at the front of the updated data, instead of the updated data itself. I've read threads such as Link 1 and Link 2 but I am unsure on how to implement it in my case. Below is my code:

Update data - Form 1

private void button1_Click(object sender, EventArgs e)
    {
        sqlConnection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Savertb.mdf;Integrated Security=True";
        sqlConnection.Open();
        cmd = new SqlCommand("UPDATE Rtbdata SET Exterior='" + RichTextBox1 + "'", sqlConnection);
        cmd.ExecuteNonQuery();
        sqlConnection.Close();
        this.Hide();
      }

Insert Updated data in datagridview - Form 2

private void button2_Click(object sender, EventArgs e)
    {
        sqlConnection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Savertb.mdf;Integrated Security=True";
        sqlConnection.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT * from Rtbdata", sqlConnection);
        sqlConnection.Close();
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;
        dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
    }
masyita shariff
  • 110
  • 1
  • 8

1 Answers1

1

You are implicitly calling RichTextBox.ToString() method which returns class name. Use Text property

    cmd = new SqlCommand("UPDATE Rtbdata SET Exterior='" + RichTextBox1.Text + "'", sqlConnection);

And take a look at parameterized sql command, it is save and convinient. Currently your code is subject to sql injection attack.

Serg
  • 22,285
  • 5
  • 21
  • 48