Friday, October 19, 2012

GridView: Getting access to it's datasource properties via DataKeyNames


Client:
<asp:GridView ID="followUpAppointments" CssClass="Report" runat="server" AutoGenerateColumns="false" Width="270"  AllowPaging="false" AlternatingRowStyle-CssClass="DataAlternateRow" CellPadding="1" CellSpacing="1" HeaderStyle-HorizontalAlign="Center" EmptyDataText="No Results."             DataKeyNames="Id,Name,Description,FollowUpList" >
                <Columns>
                    <asp:TemplateField ItemStyle-Width="10">
                        <ItemTemplate>
                            <center>
                                <asp:CheckBox ID="selectedRowCb" runat="server" />
                            </center>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Name" HeaderText="Follow Up Appointments" ItemStyle-Width="250"
                        ItemStyle-Wrap="true" />                    
                </Columns>
            </asp:GridView>


Class:
public class FollowUp
    {
        public int Id { getset; }
        public string Name { getset; }
        public string Description { getset; }
        public bool FollowUpList { getset; }
 
        public FollowUp(int id, string name, string description, bool followUpList)
        {
            this.Id = id;
            this.Name = name;
            this.Description = description;
            this.FollowUpList = followUpList;
        }
    }



Accessing on Server side:

for (int i = 0; i < followUpAppointments.Rows.Count; i++)
        {
            GridViewRow row = followUpAppointments.Rows[i];
            bool isChecked = ((CheckBox)row.FindControl("selectedRowCb")).Checked;
 
            if (isChecked)
            {
                int id = (Int32)followUpAppointments.DataKeys[i]["Id"];
                string name = followUpAppointments.DataKeys[i]["Name"].ToString();
                string description = followUpAppointments.DataKeys[i]["Description"].ToString();
                bool followup = (bool)followUpAppointments.DataKeys[i]["FollowUpList"];
 
                _selectedServices.Add(new FollowUp(id,name,description,followup));
            }
 
 
        }


No comments: