Introduction
- Here, I will explain how to display the data on click of row in GridView, using jQuery and Web Service in ASP.NET.
- Follow the steps, mentioned below, to achieve our requirement.
Step 1
Create table, using query, mentioned below.
- CREATE TABLE [tblgrid](
- [UserId] [int] IDENTITY(1,1) NOT NULL,
- [userName] [varchar](50) NULL,
- [City] [varchar](50) NULL,
- [Designation] [varchar](50) NULL,
- [sal] [bigint] NULL
- )
Step 2
Add below code to .aspx file.
Step 3
Add below code to .cs page.
- SqlConnection con = new SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=abc;Integrated Security=True");
- SqlDataAdapter da = new SqlDataAdapter();
- DataSet ds = new DataSet();
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- bind();
-
- }
- }
-
- protected void bind()
- {
-
- SqlCommand cmd = new SqlCommand("select * from tblgrid", con);
-
- da.SelectCommand = cmd;
- da.Fill(ds, "tblgrid");
- if (ds.Tables[0].Rows.Count > 0)
- {
- GridView1.DataSource = ds.Tables[0];
- GridView1.DataBind();
- }
-
- }
-
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- e.Row.Attributes.Add("onclick", "JavaScript: GetDetails('" + Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value.ToString()) + "')");
- e.Row.Attributes.Add("onmouseover", "JavaScript:this.style.cursor=’pointer’; this.style.backgroundColor=’Red’");
- e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=’white’");
- }
- }
Step 4
Create webService project.
- [WebMethod]
- public GetRec[] GetAllData(int ID)
- {
- SqlCommand cmd = new SqlCommand("select userName,City,Designation,sal from tblgrid where UserId="+ID);
- DataTable dt = new DataTable();
- cmd.Connection = con;
- da.SelectCommand = cmd;
-
- da.Fill(dt);
- List<GetRec> objList = new List<GetRec>();
- foreach(DataRow dr in dt.Select())
- {
- objList.Add(new GetRec
- {
- userName=dr["userName"].ToString(),
- City=dr["City"].ToString(),
- des = dr["Designation"].ToString(),
- sal = Convert.ToInt32(dr["sal"])
-
- }
- );
- }
- return objList.ToArray();
- }
-
- public struct GetRec {
-
- public string userName { get; set; }
- public string City { get; set; }
- public string des { get; set; }
- public int sal { get; set; }
-
- }
Step 5
We got the output, mentioned below.