views:

18

answers:

2

Hello All, I Have a set of choices(options) coming from Database(around 36 records) which I have to insert in Gridview in such a way that 18 will go one column and 18 in another. And As these are choices the columns are needs to be a check box columns. So What I did is I have created a data table with 2 columns and split the data accordingly and then bind it to the grid.But the problem is If the question list is having odd no of items count ie 37. It is adding a blank record with check box in my gridview. Your help will be appreciated... see code below In my Aspx.cs

        DataTable dTable = new DataTable();
        dTable.Columns.Add("Questionsclmn1", typeof(string));
        dTable.Columns.Add("Questionsclmn2", typeof(string));
        for (int item = 0; item < QuestionList.Count; item = item + 2)
        {
            DataRow drow = dTable.NewRow();
            drow["Questionsclmn1"] = QuestionList[item].Question;
            if ((item + 1) < QuestionList.Count)
              drow["Questionsclmn2"] = QuestionList[item + 1].Question;                
            dTable.Rows.Add(drow);
        }

        GrdVwQuestionsList.DataSource = dTable;
        GrdVwQuestionsList.DataBind();

    In my Aspx file under gridview 
    <Columns>
       <asp:TemplateField HeaderText="Please Choose the Options Below">
           <ItemTemplate>
                <asp:CheckBox  ID="chkQuestionList1" runat="server"
                 Text='<%# DataBinder.Eval( Container.DataItem, "Questionsclmn1")%>'/>
           </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField>
           <ItemTemplate>
              <asp:CheckBox  ID="chkQuestionList2" runat="server"
                Text='<%# DataBinder.Eval( Container.DataItem, "Questionsclmn2")%>'/>
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>

Thanks in Advance.

Regards, Chetan

+1  A: 

I wouldn't use a GridView for this at all. CheckboxList can lay out checkboxes in two columns automatically.

<asp:CheckboxList runat="server" RepeatLayout="Table" RepeatColumns="2" RepeatDirection="Vertical" ... />

There's also DataList that supports the same properties but lets you use a template for the content.

Matti Virkkunen
Hey Thanks Matti, I was trying the checkbox list but didn't realize I can use repeatcolumn property... Thanks for help... It's works perfect..
Chetan
A: 
for (int item = 0; item < QuestionList.Count; item = item + 2)
{
   if(!String.IsNullOrEmpty(QuestionList[item].Question)){
      DataRow drow = dTable.NewRow();
      drow["Questionsclmn1"] = QuestionList[item].Question;
      if ((item + 1) < QuestionList.Count && !String.IsNullOrEmpty(QuestionList[item].Question))
         drow["Questionsclmn2"] = QuestionList[item + 1].Question;                
      dTable.Rows.Add(drow);
   }
}

Check to make sure you have data before doing any work. I wouldn't write it this way but just to remedy the issue this will work...

Alexander