Thursday 29 June 2017

Gridview checkbox control in asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo.aspx.cs" Inherits=" Demosolution.demo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("id") %>' Visible="false"></asp:Label>
                        <asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
    </form>
</body>
</html>


using Demosolution.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demosolution
{
    public partial class demo : System.Web.UI.Page
    {
        Database1Entities db = new Database1Entities();
        tbl_Login qt = new tbl_Login();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Grid();
            }
        }
        protected void Grid()
        {
            var grid = (from a in db.tbl_Login
                        select new
                        {
                            id = a.LoginId,
                            Name= a.Login_name,
                            Email= a.Login_email,
                        }).ToList();
            GridView1.DataSource = grid.ToList();
            GridView1.DataBind();
        }
        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox activeCheckBox = (CheckBox)sender;
            foreach (GridViewRow rw in GridView1.Rows)
            {
                CheckBox chkBx = (CheckBox)rw.FindControl("CheckBox1");
                if (chkBx != activeCheckBox)
                {
                    chkBx.Checked = false;
                }
                else
                {
                    chkBx.Checked = true;
                    Label id1 = (Label)chkBx.FindControl("Label1");
                    int idd = Convert.ToInt32(id1.Text);
                    tbl_Login tb = db.tbl_Login.Where(a => a.LoginId == idd).FirstOrDefault();
                    TextBox1.Text = tb.Login_name.ToString();
                }
            }
        }
    }
}






No comments:

Post a Comment