4

Ok, so I want to populate/bind some data to a checkboxlist but cannot seem to binf the right values? I want to populate it with the information from a ROW, not the whole column which is what's happening to me. Here's some code anyways to show you what the problem is.

This is the code in the xaml

<form id="form1" runat="server">
<div>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [Option1], [Option2], [Option3] FROM [Questions] WHERE ([QuestionID] = @QuestionID)">
        <SelectParameters>
            <asp:Parameter DefaultValue="1" Name="QuestionID" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>

</div>
    <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="QuestionID" DataValueField="QuestionID">
    </asp:CheckBoxList>
</form>

This is my database (only an example one) Links are from gyazo

Questions

Data


This is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

namespace ExampleCheckbox
{
public partial class Question_One : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        SqlConnection con = new SqlConnection(connectionString);

        SqlCommand command = new SqlCommand();
        command.Connection = con;
        command.CommandType = CommandType.Text;
        command.CommandText = "Select * from Questions";

        SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
        DataSet questionsDataSet = new DataSet();


            con.Open();
            dataAdapter.Fill(questionsDataSet, "Question");

            DataTable dt = questionsDataSet.Tables["Question"];

            foreach (DataRow dr in dt.Rows)
            {
                ListItem newItem = new ListItem(dr["Option1"].ToString(), dr["QuestionID"].ToString());
                CheckBoxList1.Items.Add(newItem);
            }

            CheckBoxList1.DataSource = questionsDataSet;
            CheckBoxList1.DataTextField = "Option1";
            CheckBoxList1.DataValueField = "QuestionID";
            CheckBoxList1.DataBind();
    }
}

}


This is also the problem i'm having PROBLEM

Thanks

crsMC
  • 635
  • 3
  • 11
  • 24
  • 1
    Seems like you're looping through and binding the data manually, one by one. Have you tried removing the 4 databinding lines at the bottom? Comment those out, and let me know what you come up with. – Sean Kendle Apr 25 '14 at 19:57
  • @SeanKendle No, I havn't yet, I'm also getting the error "Both datasource and datasourceid ar not defined" when I mess around with it, but I can get rid of that error. – crsMC Apr 25 '14 at 19:59
  • 1
    I would either get rid of that loop and just bind `CheckBoxList1` with `dt`, or remove (comment out for now) the bottom 4 lines that databind *again*. Also, I would highly recommend naming your controls and variables more explicitly. Might be obvious what they are doing now, but a few months from now it's going to take twice as long to read and understand your own code. – Sean Kendle Apr 25 '14 at 20:02
  • @SeanKendle I commented them out and im still getting all the items from Option1 when I want to be able to get the values in Option1, 2, 3, etc. Thanks! – crsMC Apr 25 '14 at 20:03
  • Got rid of the loop and it still works but again, I'm still getting all the information from 'Option1' column when I want Option1, 2, 3 – crsMC Apr 25 '14 at 20:05
  • Oooh, I see what you're saying now. You're literally just adding that row over and over down a column. Let me write a proper answer. – Sean Kendle Apr 25 '14 at 20:05

1 Answers1

3

What you want to do is loop through the columns instead of the rows, and get the column names out instead.

Check out this question/answer here:

http://social.msdn.microsoft.com/Forums/en-US/4b6ede3b-093d-46f1-8766-d4a96608997d/loop-thru-a-datatable-for-columnnames-columnvalues?forum=csharpgeneral

Here's a full example. This is what your code should look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

namespace ExampleCheckbox
{
public partial class Question_One : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        SqlConnection con = new SqlConnection(connectionString);

        SqlCommand command = new SqlCommand();
        command.Connection = con;
        command.CommandType = CommandType.Text;
        command.CommandText = "Select * from Questions";

        SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
        DataSet questionsDataSet = new DataSet();


            con.Open();
            dataAdapter.Fill(questionsDataSet, "Question");

            DataTable dt = questionsDataSet.Tables["Question"];

            int i = 0;
            string str1 = string.Empty;
        int i = 0;
                    dr = dt.Rows(ClientID);   //whatever you're using for the row index
            foreach (DataColumn dc in dt.Columns)
            {
                ListItem newItem = new ListItem(dr[dc].ToString(), i.ToString());
                CheckBoxList1.Items.Add(newItem);
                i++;
            }
        }
    } 
        } 

}
Sean Kendle
  • 3,538
  • 1
  • 27
  • 34
  • 2
    If I helped you, please be sure to vote up my answer/comments that helped and accept this as an answer! I see you're kinda new here! ^_- – Sean Kendle Apr 25 '14 at 20:12
  • Yes, this has helped me, but still can't get this working, I'm still trying though. Thanks! – crsMC Apr 25 '14 at 20:16
  • 1
    Remove the 4 databinding lines for sure, and you will want to loop through each column and create a new listItem with the column's name as the "text" part of the listItem. The Data part of the listItem can be the same, if you want, or the zero-based index of the column, depending on what you're going to do with that data later. – Sean Kendle Apr 25 '14 at 20:21
  • I have removed the 4 databinding lines but I'm still not sure how to loop through the columns and create the new listitem. Later, I will want to save the data and display it at the end of the program. Any chance you could provide some example code? Thanks for your time by the way, appreciate it – crsMC Apr 25 '14 at 20:25
  • 1
    Just updated my answer. Try that on a blank page. (Obviously you'll need this on the front end: ``. The key was to loop through the columns, create a new listItem for each Column, and set the `columnName` as the `Text` value of each listItem, then add them to the `CheckBoxList1`. – Sean Kendle Apr 25 '14 at 20:30
  • Got it, thanks man, really do appreciate it as been trying to get this working for half the day and can't get any solutions. Thanks! – crsMC Apr 25 '14 at 20:32
  • 1
    Check out my latest edit, I provided what I *think* your code should be. Let me know if that works/doesn't work. – Sean Kendle Apr 25 '14 at 20:39
  • Ok, this is working now but outputting Option1, Option2, Option3, x3 – crsMC Apr 25 '14 at 20:39
  • How do I output the values inside these options? Sorry for all the questions – crsMC Apr 25 '14 at 20:39
  • 1
    Check it again, I was needlessly looping through the Rows. You only need to loop through the columns. So, it was outputting your columns for each row! d'oh! – Sean Kendle Apr 25 '14 at 20:41
  • Ok. This is what i'm getting [OUTPUT](http://gyazo.com/95ee4a11739c269e8fd13e095e89fbaa) How do I get the values inside option 1,2 and 3 with QuestionID = 1? – crsMC Apr 25 '14 at 20:43
  • 1
    I must not be understanding what you're trying to do. What exactly are you outputting? – Sean Kendle Apr 25 '14 at 20:44
  • 1
    let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/51465/discussion-between-seankendle-and-lastkingiskingin) – Sean Kendle Apr 25 '14 at 20:44