Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a checkbox column to asp.net gridview

I have a couple questions when it pertains to adding a CheckBox column to gridview in asp.net and getting multiple values. First off I see everyone adding OnCheckedChanged="chkview_CheckedChanged" to their aspx page but when you click on the CheckBox to set its actions it does not open OnCheckedChanged="chkview_CheckedChanged". It opens SelectedIndexChanged event instead. What I am trying to do is when they select a CheckBox it adds the corresponding rows info to the TextBox. Here is what I am currently using to set the values. How can I use a selected CheckBox instead?

protected void dropGridView_SelectedIndexChanged1(object sender, EventArgs e)
{
    GridViewRow row = dropdeadGridView.SelectedRow;
    IDTextBox.Text = row.Cells[1].Text;
    loadnumTextBox.Text = row.Cells[2].Text;
}

Once done with that how can you make it to where it will get every row that is checked instead of just one which is what is my current problem. I am looking for a way to select multiple rows and have a select button. I have done a lot of looking and can find nothing on it so I am trying to accomplish this with CheckBoxes instead. Any ideas how I can add this and get the multiple rows that can be selected. Thank you in advance.

Here is my edit* Posting asp code for CheckBox column:

<asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="SelectCheckBox" runat="server" OnCheckedChanged="SelectCheckBox_OnCheckedChanged"/>
            </ItemTemplate>
        </asp:TemplateField>
like image 703
Kpt.Khaos Avatar asked Mar 07 '14 14:03

Kpt.Khaos


People also ask

How can check CheckBox checked in GridView in ASP NET?

Gridview with a select-button, a boundfield and a checkbox. Binding the data to the gridview works fine. (the data in the DB has an NVARCHAR column for the bounfield and a BIT column for the checkbox.


1 Answers

First you have to set autopostback attribute to true :

<asp:CheckBox ID="SelectCheckBox" runat="server" AutoPostBack="true" 
              OnCheckedChanged="SelectCheckBox_OnCheckedChanged"/>

In your case, SelectedIndexChanged is sent by the gridview. For the checkbox event you have to use OnCheckedChanged event :

protected void SelectCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = sender as CheckBox ;

    if(chk.Checked)
    {
        GridViewRow row = (GridViewRow)chk.NamingContainer;
        IDTextBox.Text = row.Cells[1].Text;
        loadnumTextBox.Text = row.Cells[2].Text;
    }
}

If you want to loop through all selected checkboxes :

var rows = dropdeadGridView.Rows;
int count = dropdeadGridView.Rows.Count;
for (int i = 0; i < count; i++)
{
    bool isChecked = ((CheckBox)rows[i].FindControl("chkBox")).Checked;
    if(isChecked)
    {
        //Do what you want
    }
}
like image 130
Plue Avatar answered Sep 27 '22 18:09

Plue