HI friends,
in this article I will explain about Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in ASP.NET using C# or VB.NET.
I already explained in the previous articles about How to validate CheckBoxList in ASP.NET using JavaScript || Select atleast one item validation for ASP.Net CheckBoxList,How to insert multiple rows into the GridView without using any database in ASP.NET using VB.NET/C# || how to save multiple rows in GridView into a Session and How to insert the data from the TextBox into the Grid View without using any database in ASP.NET using VB.NET/C#
C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
public partial class EditGrid : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData();
}
}
protected void bindData()
{
SqlCommand cmd = new SqlCommand("select * from user_data", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grd.DataSource = ds;
grd.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grd.DataSource = ds;
grd.DataBind();
int columncount = grd.Rows[0].Cells.Count;
grd.Rows[0].Cells.Clear();
grd.Rows[0].Cells.Add(new TableCell());
grd.Rows[0].Cells[0].ColumnSpan = columncount;
grd.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void grd_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
grd.PageIndex =
e.NewPageIndex;
bindData();
}
protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
{
grd.EditIndex =
e.NewEditIndex;
bindData();
}
protected void grd_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grd.EditIndex = -1;
bindData();
}
protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
grd.EditIndex = -1;
int id = Convert.ToInt32(((TextBox)(grd.Rows[e.RowIndex].FindControl("txtUid"))).Text);
string username = ((TextBox)(grd.Rows[e.RowIndex].FindControl("txtUname"))).Text;
string lastname = ((TextBox)(grd.Rows[e.RowIndex].FindControl("txtLname"))).Text;
SqlCommand cmd= new SqlCommand("update user_data set username= '" + username + "'
,lastname='" + lastname + "' where userid= ' " + id + " ' ", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindData();
}
protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(((Label)(grd.Rows[e.RowIndex].FindControl("lblUID"))).Text);
SqlCommand cmd = new SqlCommand("delete user_data where userid= ' " + id + " ' ", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindData();
}
}
|
ASP.NET Code
|
VB.NET
|
Click here VB.NET code
|
No comments:
Post a Comment