C# Tutorials and offshore development in India

Tutorials Resources Forum Reviews Interview Jobs Projects Training Your Ad Here


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...




Forums » .NET » .NET »

How to use auto edit update cancel in gridview


Posted Date: 25 May 2009      Posted By: anbu      Member Level: Gold     Points: 1   Responses: 2



how to use auto edit update cancel in gridview
pls giv some ex in source code





Responses

Author: DotNetMatrix    25 May 2009Member Level: GoldRating: 3 out of 53 out of 53 out of 5     Points: 3

You will get more information in this link http://www.codeproject.com/KB/aspnet/UsePayPalPaymentInASPNET.aspx

Thanks for Sharing
DotNetMatrix



Author: Syed Shakeer Hussain     25 May 2009Member Level: DiamondRating: 4 out of 54 out of 54 out of 54 out of 5     Points: 6

Hi

<asp:Label ID="lblMessage" runat="Server" ForeColor="Red"></asp:Label>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False" BorderWidth="1"
DataKeyNames="AutoID" AutoGenerateEditButton="True" OnRowEditing="EditRecord"
OnRowCancelingEdit="CancelRecord" OnRowUpdating="UpdateRecord" CellPadding="4"
HeaderStyle-HorizontalAlign="left" OnRowDeleting="DeleteRecord" RowStyle-VerticalAlign="Top"
ForeColor="#333333" GridLines="None">
<Columns>
<asp:BoundField DataField="AutoID" HeaderText="AutoID" ReadOnly="True" />
<asp:TemplateField HeaderText="Page Name">
<ItemTemplate>
<%# Eval("PageName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPageName" runat="Server" Text='<%# Eval("PageName") %>' Columns="30"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" runat="Server" Text="*" ControlToValidate="txtPageName"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Page Description">
<ItemTemplate>
<%# Eval("PageDescription") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPageDesc" runat="Server" TextMode="MultiLine" Rows="10" Columns="50"
Text='<%# Eval("PageDescription") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" runat="Server" Text="*" ControlToValidate="txtPageDesc"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<%# Eval("Active") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active").ToString().ToLower().Equals("true") ? "True" : "False" %>'>
<asp:ListItem Text="Yes" Value="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandName="Delete"></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" VerticalAlign="Top" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>




Populating the GridView Control

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

/// <summary>
/// Bind data to the grid
/// </summary>
private void BindData()
{
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter dAd = new SqlDataAdapter("select * from mySampleTable", conn);
DataSet dSet = new DataSet();
try
{

dAd.Fill(dSet, "PagesData");
GridView1.DataSource = dSet.Tables["PagesData"].DefaultView;
GridView1.DataBind();
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
dSet.Dispose();
dAd.Dispose();
conn.Close();
conn.Dispose();
}
}

To populate the GridView, I am calling BindData() method from Page_Load event after checking IsPostBack property of the page, so the GridView will only be populated when there is no postback on the page (when the page loads for the first time). This will make sure that BindData() method will not fire when you are going to edit, update or delete the record.

In BindData() method, I am getting the data from database using Sql objects and specifying the DataSource property of the GridView to the PagesData table of the DataSet.



Editing GridView Control

/// <summary>
/// fires when edit link is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditRecord(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}


When Edit link of the GridView will be clicked then OnRowEditing event will fire that will call EditRecord method. In this method, I am specifying the EditIndex property of the GridView to the NewEditIndex of the GridView and then calling BindData() method again to bind the data. Please note that when you will not bind the data again, GridView will not change in edit mode.




Cancel Editing GridView Control

/// <summary>
/// fires when cancel link is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CancelRecord(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}

When Cancel link is clicked on GridView in edit mode, OnRowCancelingEdit event will fire that will call CancelRecord method. In this method, I am specifying the EditIndex property of the GridView to -1. As there is no row at -1 position so GridView will be shown in normal mode.




Updating
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

int autoid = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox tPageName = (TextBox)row.FindControl("txtPageName");
TextBox tPageDesc = (TextBox)row.FindControl("txtPageDesc");
DropDownList dActive = (DropDownList)row.FindControl("dropActive");

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ToString());
SqlCommand dCmd = new SqlCommand();
try
{
conn.Open();
dCmd.CommandText = "spUpdateData";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("@AutoID", SqlDbType.Int).Value = autoid;
dCmd.Parameters.Add("@PageName", SqlDbType.VarChar, 50).Value = tPageName.Text.Trim();
dCmd.Parameters.Add("@PageDescription", SqlDbType.VarChar, 500).Value = tPageDesc.Text.Trim();
dCmd.Parameters.Add("@Active", SqlDbType.Bit).Value = bool.Parse(dActive.SelectedValue);
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();

lblMessage.Text = "Record Updated successfully.";


// Refresh the data
GridView1.EditIndex = -1;
BindData();
}
catch (SqlException ee)
{
lblMessage.Text = ee.Message;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}

}



Deleting REcord
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
string autoid = GridView1.DataKeys[e.RowIndex].Value.ToString();

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ToString());
SqlCommand dCmd = new SqlCommand();
try
{
conn.Open();
dCmd.CommandText = "spDeleteData";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("@AutoID", SqlDbType.Int).Value = Int32.Parse(autoid);
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();

lblMessage.Text = "Record Deleted successfully.";

// Refresh the data
BindData();

}
catch (SqlException ee)
{
lblMessage.Text = ee.Message;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}

When Delete link of the GridView will be clicked, it will confirm the user whether they really want to Delete the record, if they will click OK, it will fire OnRowDeleting event of the GridView that will call DeleteRecord method. In this method again, I am getting the primary key value using DataKeys property of the GridView and using it to delete the records from the database. After successfully deleting records, again I am calling BindData() method to rebind the GridView.





Thanks & Regards!
Syed Shakeer Hussain



Post Reply

 This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.


Next : How to distinguise points of lines and curves ???
Previous : Change gridview header text
Return to Discussion Forum
Post New Message
Category: .NET

Related Messages




About Us    Contact Us    Privacy Policy    Terms Of Use