Phillip Andrews
Phillip Andrews

Reputation: 49

asp gridview with checkbox and select

I am trying to develop an asp c# gridview that has select so that I can display additional details of the record. I also need a check box to allow the user the check the row for further processing. I can achieve each separately but not together. Is it even possible?

Upvotes: 1

Views: 2808

Answers (3)

Mr G
Mr G

Reputation: 51

<asp:TemplateField>
    <ItemTemplate>
        <asp:CheckBox ID="SelectChk" OnCheckedChanged="chk_Click1" runat="server" AutoPostBack="true" />
    </ItemTemplate>
</asp:TemplateField>

And in the CS code:

protected void chk_Click1(object sender, EventArgs e)
{
    CheckBox MChk = sender as CheckBox;
    GridViewRow MyGridR = MChk.NamingContainer as GridViewRow;
    GridView1.SelectRow(MyGridR.RowIndex);
}                    

Upvotes: 0

Dusan
Dusan

Reputation: 5144

Of course it is possible. For the column of check boxes, use TemplateField column, https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield%28v=vs.110%29.aspx

In data grid, aspx:

<asp:TemplateField>
    <ItemTemplate>
        <asp:CheckBox ID="CheckBoxProcess" runat="server" />
    </ItemTemplate>
</asp:TemplateField>

In code behind:

protected void ButtonProcess_Click(object sender, EventArgs e)
{
    foreach (GridViewRow item in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)item.FindControl("CheckBoxProcess");
        if (chk != null)
        {
            if (chk.Checked)
            {
                // This record should be processed
            }
        }
    }
}

The GridView has build in row select functionality, you can enable it by setting AutoGenerateSelectButton property to true:

<asp:GridView ... AutoGenerateSelectButton="true" />

However, it is more user friendly to select the row when user clicks on it (rather than clicking on the link). To do this, you need to attach a bit of java-script to the row:

void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
        e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(sender, "Select$" + e.Row.RowIndex.ToString())
}

Here is also, much better explained solution for row click select:

https://stackoverflow.com/a/6250846/461810

Upvotes: 2

Jon
Jon

Reputation: 636

You can use template fields and just add the controls into them.

<Columns>                             
    <asp:TemplateField>
        <ItemTemplate> 
            <select />
        </ItemTemplate>
    </asp:TemplateField>             
    <asp:TemplateField>
        <ItemTemplate> 
            <checkbox />
        </ItemTemplate>
    </asp:TemplateField>                  
</Columns> 

Upvotes: 0

Related Questions