Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm having trouble getting the edit button in the datagridview to work properly.I need the edit button when selected to put the text back in the orginal textbox for editting then be able to hit the update button to update that data. I know I'm doing something wrong but I don't know what it is. If someone could look it over and help me figure out what I'm doing wrong that would be great!

This is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ProgressReports
{
  public partial class ReportsForm : Form
  {
    public ReportsForm()
    {
      InitializeComponent();
    }

    private void ReportsForm_Load(object sender, EventArgs e)
    {
      string connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\eliza\ReportsDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

      SqlConnection con = new SqlConnection(connectionString);
      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Database_tbl", con);

      DataSet ds = new DataSet();
      da.Fill(ds, "Database_tbl");

      ReportDataGrid.DataSource = ds.Tables["Database_tbl"].DefaultView;

      // TODO: This line of code loads data into the 'reportsDatabaseDataSet.Database_tbl' table. You can move, or remove it, as needed.

      this.database_tblTableAdapter.Fill(this.reportsDatabaseDataSet.Database_tbl);

    }

    private void Submit_Click(object sender, EventArgs e)
    {
      string connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\eliza\ReportsDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

      SqlConnection con = new SqlConnection(connectionString);
      con.Open();

      SqlCommand cmd = new SqlCommand("INSERT INTO Database_tbl (EntryDate, ReportText) VALUES ('" + DateTime.Now + "','" + ReportText.Text + "')", con);

      cmd.ExecuteNonQuery();
      con.Close();

      MessageBox.Show("Report Successfully Added");

      ReportDataGrid.Update();

      ReportText.Text = "";     
    }


//This is where I'm having the problem at

private void ReportDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      {
        if (ReportDataGrid.Columns[e.ColumnIndex].Name == "Edit")
        {
          int i = ReportDataGrid.CurrentCell.RowIndex;
          int j = ReportDataGrid.CurrentCell.ColumnIndex + 3;
          int x = ReportDataGrid.CurrentCell.ColumnIndex + 1;

        ReportText.Text = ReportDataGrid.Rows[i].Cells[j].Value.ToString();

          lblRowID.Text = ReportDataGrid.Rows[i].Cells[x].Value.ToString();

          btnUpdate.Visible = true;

          Submit.Visible = false;
        }
      }
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {

      string connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\eliza\ReportsDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

      SqlConnection con = new SqlConnection(connectionString);
      con.Open();

      SqlCommand cmd = new SqlCommand("Update Database_tbl set ReportText = '" + ReportText.Text + "' Where EntryID = " + lblRowID.Text + "')", con);

      cmd.ExecuteNonQuery();
      con.Close();

      MessageBox.Show("Report Successfully Updated");

      ReportDataGrid.Update();

      ReportText.Text = "";
    }
  }
}


What I have tried:

This is what I've tried so far

C#
private void ReportDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
      {
        if (ReportDataGrid.Columns[e.ColumnIndex].Name == "Edit")
        {
          int i = ReportDataGrid.CurrentCell.RowIndex;
          int j = ReportDataGrid.CurrentCell.ColumnIndex + 3;
          int x = ReportDataGrid.CurrentCell.ColumnIndex + 1;

        ReportText.Text = ReportDataGrid.Rows[i].Cells[j].Value.ToString();

          lblRowID.Text = ReportDataGrid.Rows[i].Cells[x].Value.ToString();

          btnUpdate.Visible = true;

          Submit.Visible = false;
        }
      }
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
      string connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\eliza\ReportsDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

      SqlConnection con = new SqlConnection(connectionString);
      con.Open();

      SqlCommand cmd = new SqlCommand("Update Database_tbl set ReportText = '" + ReportText.Text + "' Where EntryID = " + lblRowID.Text + "')", con);

      cmd.ExecuteNonQuery();
      con.Close();

      MessageBox.Show("Report Successfully Updated");

      ReportDataGrid.Update();

      ReportText.Text = "";
    }
  }
}
Posted
Updated 14-Apr-20 16:10pm
v2
Comments
Garth J Lancaster 14-Apr-20 22:24pm    
Howdy - you dont actually say what the problem is, and Im not 100% clear from your description what your form looks like (always hard in this forum)

So, if I understand,

a) you have a datagrid
b) you have a textbox for 'original' text
c) you have an update button
AND
d) when you click a row in the datagrid (I assume/presume this is being populated)
e) you'd like 'text' from row/column to be put into the textbox where it can be edited
f) when you hit the update button, you'd like to update that row/column with the information from the testbox

yes ?

Some things to check .. do these variables/the update text box get populated

>>ReportText.Text = ReportDataGrid.Rows[i].Cells[j].Value.ToString();
>>lblRowID.Text = ReportDataGrid.Rows[i].Cells[x].Value.ToString();

What does 'cmd' end up with here ?

>> SqlCommand cmd = new SqlCommand("Update Database_tbl set ReportText = '" + ReportText.Text + "' Where EntryID = " + lblRowID.Text + "')", con);

Also .. that not a good way to handle the SQL, please google for 'parameterised sql query'

Lastly .. Have a look at this style

// In a using statement, acquire the SqlConnection as a resource.
//
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// Do stuff
}
Richard Deeming 16-Apr-20 7:18am    
SqlCommand cmd = new SqlCommand("Update Database_tbl set ReportText = '" + ReportText.Text + "' Where EntryID = " + lblRowID.Text + "')", con);

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
using (SqlCommand cmd = new SqlCommand("Update Database_tbl set ReportText = @ReportText Where EntryID = @EntryID", con))
{
    cmd.Parameters.AddWithValue("@ReportText", ReportText.Text);
    cmd.Parameters.AddWithValue("@EntryID", lblRowID.Text);
    cmd.ExecuteNonQuery();
}
Member 14802172 21-Apr-20 11:53am    
So I keep getting the same error everytime System.Data.SqlClient.SqlException: 'Invalid column name 'EntryID'.'
This is my table in design view:
CREATE TABLE [dbo].[Database_tbl] (
[EntryID] INT IDENTITY (1, 1) NOT NULL,
[EntryDate] SMALLDATETIME NOT NULL,
[ReportText] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([EntryID] ASC)
);
So the EntryID is in fact there but I'm getting this error and not sure why..
Richard Deeming 21-Apr-20 12:00pm    
Make sure you're connecting to the correct server and database.

Try specifying the schema name in your query:
Update dbo.Database_tbl set ReportText = @ReportText Where EntryID = @EntryID
Member 14802172 21-Apr-20 13:42pm    
So I think I fixed that issue but now i'm getting this error System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value '4/21/2020 12:26:00 PM' to data type int.'

I don't know why it would try to convert that. When I edit the selected column it should let me update the text, click the update button and replace what was orginally in that column with the updated text and smalldatetime.

I'm sorry I'm so much trouble. I've never worked with anything like this before and I'm having to create this entire project myself from the ground up. I'm learning as I go. Thank you for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900