Show a Checkbox filed inside a grid view in Asp.Net C#
  • Hello
    I am creating an Attendance system for my Institute, What i want to do i have a grid view that contains Names and Roll numbers of Students, I want to show an extra column having a check boxes so that when some check the check box and clicks Save then Attendance for that student is recorded. Please see below image for details: 

    image
    attandance.jpg
    954 x 387 - 87K
  • 1 Comment sorted by
  • Vote Up1Vote Down ithackerithacker
    117.50 Karma Accepted Answer
    hi sajid kindly use this code for manage checkbox in gridview and then update for database.

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"  
        CellPadding="0" DataKeyNames="CategoryID" Font-Size="10pt"
        Font-Names="Arial" GridLines="Vertical" Width="40%">
               
                <Columns>            
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkStatus" runat="server"
                                AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
                                Checked='<%# Convert.ToBoolean(Eval("Present")) %>'
                                Text='<%# Eval("Present").ToString().Equals("True") ? " Present " : " Not Present " %>' />
                        </ItemTemplate>                   
                    </asp:TemplateField>
                   
                    <asp:BoundField DataField="RollNo" HeaderText="RollNo" />                   
                    <asp:BoundField DataField="StudentName" HeaderText="StudentName"  />
                </Columns>
               
    </asp:GridView>

    and in .cs file use this.
    public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
    {
    CheckBox chkStatus = (CheckBox)sender;
    GridViewRow row = (GridViewRow)chkStatus.NamingContainer;


    string cid = row.Cells[1].Text;
    bool status = chkStatus.Checked;


    string constr = @"Data Source=.\SqlExpress;Initial Catalog=YourDatabaseName;Integrated Security=True";
    string query = "UPDATE tblAttendance SET Present = @Present WHERE RollNo = @RollNo";

    SqlConnection con = new SqlConnection(constr);
    SqlCommand com = new SqlCommand(query, con);


    com.Parameters.Add("@Present", SqlDbType.Bit).Value = status;
    com.Parameters.Add("@RollNo", SqlDbType.Int).Value = cid;


    con.Open();
    com.ExecuteNonQuery();
    con.Close();

    //again fill gridview data.
    }


Howdy, Stranger!

It looks like you're new here. If you want to get involved, or you want to Ask a new Question, Please Login or Create a new Account by Clicking below

Login with Facebook

Tagged

Popular Posts of the Week

Top Posters Weekly

Optimum Creative