开发者

how to populate a list from a asp .net grid view?

I have a Grid View, I want to update all the rows that will be selected by checking the checkbook. First I want all the selected rows into a list. I don know how to do it. I know how to populate a grid from a list. my grid view is

<asp:GridView runat="server" ID="GridForResult" 
        Visible="true" 
        ShowHeader="false"
        AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField ItemStyle-Width="120px" ItemStyle-Height="22px">
            <ItemTemplate>
                <%#Eval( "TestRoll")%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ItemStyle-Width="150px" ItemStyle-Height="22px">
            <ItemTemplate>
                <%#Eval( "Name")%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ItemStyle-Width="80px" ItemStyle-Height="22px">
            <ItemTemplate>
                <%#Eval( "Program")%>
            </ItemTemplate>
        </开发者_JAVA技巧asp:TemplateField>
        <asp:TemplateField ItemStyle-Width="80px" ItemStyle-Height="22px">
            <ItemTemplate>
                <asp:CheckBox ID="chkSelected" runat="server" Text="Selected" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

My another problem is How to get only the selected (checkboxes) rows from the gridview?


Its pretty straight forward if you are not paging your grid and you want to maintain checked value on PostBack. On GridView Markup, set DataKeyNames="{your primary key}"

Code - behind

List<string> primaryKeys = new List<string>();
foreach(GridViewRow row in GridForResult.Rows)
{
    CheckBox check = row.FindControl("chkSelected") as CheckBox;
    if(check.Checked)
    {
        primaryKeys.Add(GridForResult.DataKeys[row.RowIndex].Value.ToString());
    }
}

The List<string> primaryKeys will now hold all the checked primary keys.


List<string> objList = new List<string>();        

foreach (GridViewRow gvrow in GridView1.Rows)
{
    CheckBox CheckBox1 = (CheckBox)gvrow.FindControl("CheckBox1");
    if (CheckBox1.Checked)
    {
      objList.Add(row["id"].Text);    
    }
}


I would make the checkboxes column a TemplateColumn. Then on postback you need to iterate the GridView Rows Collection and do something like this:

foreach(GridViewRow row in gridViewId)
{
    CheckBox chk = row.FindControl("CheckBoxId") as CheckBox;//use chk value as needed
}


declare a collection of say string type,
List<string> objList = new List<string>();

foreach(GridViewRow row in gridViewId)
{
    CheckBox chk = row.FindControl("CheckBoxId") as CheckBox;
    if(chk.IsChecked)
    {
     objList.Add(row["id"].Text);
    }
}
save this list in session,
Session["checkedList"] = objList;

when you want to retireve,use,
objList = List<string>(Session["checkedList"]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜