ASP.NET Gridview: How to Edit and Delete Data Records

ASP.NET GridView: How to edit and delete data records

The GridView supports those operations. You can add a CommandField which will contain the command buttons or LinkButtons (you can choose the type of button and assign the text of each button). The patientID field should be included in the DataKeyNames property of the GridView, in order to retrieve it when the time comes to update or delete the record in the database.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="patientID"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" />
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
...
</Columns>

You will then need to handle a few events in code-behind:

// The RowEditing event is called when data editing has been requested by the user
// The EditIndex property should be set to the row index to enter edit mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}

// The RowCancelingEdit event is called when editing is canceled by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}

// The RowUpdating event is called when the Update command is selected by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
string surgery = (string)e.NewValues["surgery"];
string location = (string)e.NewValues["location"];

// Update here the database record for the selected patientID

GridView1.EditIndex = -1;
BindData();
}

// The RowDeleting event is called when the Delete command is selected by the user
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int patientID = (int)e.Keys["patientID"]

// Delete here the database record for the selected patientID

BindData();
}

Since the data must be bound to the GridView at the end of each of those event handlers, you can do it in a BindData utility function, which should also be called when the page loads initially:

private void BindData()
{
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}

Add and Delete Rows From ASP.NET GridView

Not at all clear why you have all that extra code in add row????

If you want to default values, why not take them from the persisted datatable, and why bother with the grid??? - I don't think you need all that code.

Now, to make this really work? You do want a extra routine - Grid to table.

but, lets leave that for now.

2nd, note that because data table is a object, once you point the object to viewstate, then changes ALSO point back to view state (you don't have to re-save back into viewstate. With a string, or int counter - yes you do, but not with objects (since then you only really working with a pointer to the given object).

Also, don't bother with the built in GV delete button - it really is more pain then it is worth. Just drop in a button into the GV, and wrire up a click event. That way you don't have to mess with the row data bound event to shove in the client side confirm you have.

Also, for most grids, you don't need to show/display/include/have the row ID. In fact for reasons of secuirty, in most cases I don't display the database PK row id (and you don't have to).

And one more FYI: When you start to add a LOT of custom controls to a grid view? Well, it always painful that each custom control needs that template tags. And with quite a few controls, that becomes really messy fast. So, I suggest a ListView, as each custom control dropped into the ListView does not requite those template tags. But, lets leave this tip for next around around.

Also, MANY do not realize that you can send a whole datatalbe BACK to the database if the datatable came from a database, and can execute this save back WITH ONE command that will automatic write back all updates, inserts and even deletes. Of course in your example, we just playing and building a 100% in-memory data table, but this whole setup works near the same if/when the datatable was from a database.

So, I would dump the built in delete button.

I would dump the row data bound code.

I also would consider moving the add button OUT of the GV. You can turn on "ShowHeaderWhenEmpty" = true. that will THEN display the header - even without data. But without data, the footer DOES NOT show, and thus if you delete the one row, you be unable to add that row.

So, our markup is this:

NOTE close, I did not want to write code to load up each row - we don't have to, so note how I added the Text = expression. Again, less code.

<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" 
AutoGenerateColumns="false" CssClass="table"
ShowHeaderWhenEmpty="true" Datakeys="RowNumber" >
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>' ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" cssclass="btn"/>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText ="Delete">
<ItemTemplate>
<asp:Button ID="cmdDelete" runat="server" Text="Delete" CssClass="btn"
OnClick="cmdDelete_Click"
OnClientClick = '<%# "return confirm(\"Really delete this row " +
Container.DisplayIndex + " (" +
Eval("RowNumber") + ")" + "\");" %>'
/>
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

And HOW you start the page up? Beyond important!!!

So, we have this code:

   DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
SetInitialRow();
else
dt = ViewState["CurrentTable"] as DataTable;
}

private void SetInitialRow()
{
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns[0].AutoIncrement = true;
//Set the Starting or Seed value.
dt.Columns[0].AutoIncrementSeed = 1;
//Set the Increment value.
dt.Columns[0].AutoIncrementStep = 1;

dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));

dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);

ViewState["CurrentTable"] = dt;

Gridview1.DataSource = dt;
Gridview1.DataBind();
}

Note how I moved the table to class level.

Now code to add is this:

    protected void ButtonAdd_Click(object sender, EventArgs e)
{
GridToTable();

DataRow MyNewRow = dt.NewRow();
dt.Rows.Add(MyNewRow);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}

And code to delete is this:

    protected void cmdDelete_Click(object sender, EventArgs e)
{
GridToTable();

Button cmdDel = sender as Button;
GridViewRow gRow = cmdDel.NamingContainer as GridViewRow;

// get row to delete

int RowDel = gRow.RowIndex;

dt.Rows[RowDel].Delete();
Gridview1.DataSource = dt;
Gridview1.DataBind();
}

So, as noted, above quite much makes this work. As noted, if we are to allow editing of the data (assume yes), then we need one more routine that moves grid back to data.

So, when you hit a save button, we call GridToTable.

So, when you hit a add button, we call Grid to Table.

So, when you hit delete button, we call Grid to table.

In other words, we REALLY need to save all edits BACK to the table before we add, or delete or even want to save the table to a database.

So, we need this routine:

    void GridToTable()
{
// send current grid back to table.
foreach (GridViewRow gRow in Gridview1.Rows)
{
DataRow OneRow = dt.Rows[gRow.RowIndex];

OneRow["Column1"] = (gRow.FindControl("TextBox1") as TextBox).Text;
OneRow["Column2"] = (gRow.FindControl("TextBox2") as TextBox).Text;
OneRow["Column3"] = (gRow.FindControl("TextBox3") as TextBox).Text;
}
}

Gridview Edit Delete and Update in ASP.NET

First sight:

Since P_Id column has VARCHAR(10) datatype, I figured out you forget to include some additional apostrophes on UPDATE & DELETE clause. The correct form of SQL statements should be this (notice additional apostrophe signs around P_Id column):

string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + "' WHERE P_Id= '" + P_Id + "'";

and

string query = "DELETE FROM practice WHERE P_Id='" + id + "'";

Only string values require apostrophes around them, numbers do not.

How to Perform delete and Edit in sql from grid view in C#

you can use as shown below.
For Insert from the gridview Design columns tag

<Columns>   
<FooterTemplate>
<asp:LinkButton ID="btnAddNew" Text="Add New" runat="server" CommandName="AddNew" ToolTip="ADD"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>

protected void EmpGrid_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtf = (TextBox)EmpGrid.FooterRow.FindControl("txtFooterFname");
TextBox txtl = (TextBox)EmpGrid.FooterRow.FindControl("txtfooterLname");
TextBox txtq =
(TextBox)EmpGrid.FooterRow.FindControl("txtfooterqualification");
TextBox txtd =
(TextBox)EmpGrid.FooterRow.FindControl("txtfooterdecription");
TextBox txts = (TextBox)EmpGrid.FooterRow.FindControl("txtfootersalary");

// For Inserting New Row
string insrtquery = "insert into EMPTable
(fname,lname,qualification,designation,sal) values
('" + txtf.Text + "','" + txtl.Text + "',
'" + txtq.Text + "','" + txtd.Text + "','" +
txts.Text + "')";
da = new SqlDataAdapter(insrtquery, con);
DataSet ds = new DataSet();
da.Fill(ds,"inserted");
Bindemployees();
}
}

protected void EmpGrid_Updating(object sender, GridViewUpdateEventArgs e)
{
int empid = Convert.ToInt32(EmpGrid.DataKeys[e.RowIndex].Value.ToString());
string fname = EmpGrid.DataKeys[e.RowIndex].Values["fname"].ToString();
string lname = EmpGrid.DataKeys[e.RowIndex].Values["lname"].ToString();
TextBox txtq =
(TextBox)EmpGrid.Rows[e.RowIndex].FindControl("txtEditqualification");
TextBox txtd =
(TextBox)EmpGrid.Rows[e.RowIndex].FindControl("txtEditdesignation");
TextBox txts =
(TextBox)EmpGrid.Rows[e.RowIndex].FindControl("txtEditsalary");

string updatequery = "update EMPTable set qualification='" + txtq.Text +
"',designation='" + txtd.Text + "',sal='" + txts.Text + "'
where empid='" + empid + "'";
DataSet ds = new DataSet();
da = new SqlDataAdapter(updatequery,con);
da.Fill(ds,"added");
EmpGrid.EditIndex = -1;
Bindemployees();
}

protected void EmpGrid_Deleting(object sender, GridViewDeleteEventArgs e)
{
int empid = Convert.ToInt32(EmpGrid.DataKeys[e.RowIndex].Value.ToString());
da = new
SqlDataAdapter("delete from EMPTable where empid='" + empid + "'", con);
DataSet ds = new DataSet();
da.Fill(ds,"deleted");
Bindemployees();
}

For better understanding see this link

http://reddyinfosoft.blogspot.in/2012/07/insert-edit-update-and-delete-with-in.html

Create a custom delete and edit in gridview using asp.net?

The cell does not contain Text but does contain a Label. I would try this:

var cell = GridView1.Rows[gridrow.RowIndex].Cells[4];
string name = ((Label)cell.FindControl("Label1")).Text;


Related Topics



Leave a reply



Submit