Cant View CheckBoxList from the database - c#

I have 2 pages , one to add data to database , and the other to edit it, so in the add I have a CheckBoxList , I added them as follow in the database
URLS : 1,2,3,4,5
and the numbers are the values "keys" from the checkbox
I used this code
String values = "";
foreach (ListItem i in CheckBoxList1.Items)
{
if (CheckBoxList1.Items.Count == 1)
values += i.Value;
else
if (i.Selected)
{
values += i.Value + ",";
}
}
and then I added the values to the database , and it worked perfect ,
now my problem is in the edit page ,as first I want to show the checked boxes from the database , I used this but its not working
in the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
... connection to the database .. etc
try
{
con.Open();
rd = cmd.ExecuteReader();
if (rd.Read())
{
String values = rd["urls"].ToString();//workes perfect
string[] arr = values.Split(',');//works perfect
int x = CheckBoxList1.Items.Count;//this will get me a zero
foreach (ListItem item in CheckBoxList1.Items)// doesnt enter here
{
foreach (string s in arr)
{
if (item.Text == s)
{
item.Selected = true;
}
}
}
.... //exceptions handling
my code for the aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="urls_ds"
DataTextField="name" DataValueField="id">
</asp:CheckBoxList>
<asp:SqlDataSource ID="urls_ds" runat="server"
ConnectionString="<%$ ConnectionStrings:testing_cs %>"
SelectCommand="SELECT * FROM [tbl_urls]"></asp:SqlDataSource>
I am getting the checkboxlist from the database using SqlDataSource , and in the page I can see them put as I print the count of the items its zero
where could be the problem ??
Thanks

Edit : This post describes your problem exactly http://forums.asp.net/t/1488957.aspx/1, and offers two solutions
Here is what I see
if(!Page.IsPostBack)
This means you are on a NEW copy of the page, so CheckBoxList1 is empty until you load it with data. which I bet happens further down in your code. Just make sure you load it before you use it.
Edit : When using a SqlDataSource to populate controls, you must remember that controls referencing it bind AFTER Page_Load execution. The link above gives two work around methods (either manually calling Control.DataBind or handling the Control.Databound event).

Related

How to calculate multiple selected Datavalue from Listbox in asp.net webforms

Basically I'm trying to make a quiz application (multiplechoice questions) and I want to calulate the total number of correct answers based on the data value from the database.
So I've used Listbox inside a repeater to show the choices which looks like the following:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
Q-<%# Eval("Question_Text") %><br />
<asp:ListBox ID="ListBox1" runat="server" CssClass="listboxCSS"></asp:ListBox><br /> <br />
</ItemTemplate>
</asp:Repeater>
and the C# code look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlCalss Obj = new SqlCalss();
Repeater1.DataSource = Obj.ExecuteCmdSelect("SELECT * from Questions where ExamId=1");
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object source, RepeaterItemEventArgs e)
{
string choice = DataBinder.Eval(e.Item.DataItem, "Question_Id").ToString();
SqlCalss Obj = new SqlCalss();
DataSet Ds = new DataSet();
Ds = Obj.ExecuteCmdSelect("SELECT * from Choices where QuestionId="+choice);
ListBox ListBox1 = (ListBox) (e.Item.FindControl("ListBox1"));
ListBox1.DataSource = Ds;
ListBox1.DataTextField = "Choice_Text";
ListBox1.DataValueField = "Answer";
ListBox1.DataBind();}
The code works good, it show multiple question ( it depends on the quiz) with multiple choices for each question shown in a Listbox.
now for each question,the DataValueField can have only one of two values( 0 = wrong , 1= correct ). In addition the total number of questions is different from one survey to another so I don't know how many Listboxes are there.
How can Add a button that Calculate all the selected datavalues to show the total correct answers ?
I tried this code:
int x = Repeater1.Controls.Count(x => x.DataValueField == 1);
and this
int numCorrect = Repeater1.Items.Count(x => x.DataValueField == 1);
Edit:
When I run the web page, for example a quiz that has two questions ( each question has four choices in listbox )
I found that when I view the source of the web page it creates two listboxes with the same name like this:
<select size="4" name="Repeater1$ctl00$ListBox1" id="Repeater1_ListBox1_0" class="listboxCSS">
....
<select size="4" name="Repeater1$ctl01$ListBox1" id="Repeater1_ListBox1_1" class="listboxCSS">
and I figured out how to get the value of the first one using code like this:
ListBox ListBox1 = (ListBox)this.FindControl("Repeater1$ctl00$ListBox1");
Response.Write(ListBox1.SelectedValue.ToString());
Is there anyway that I can get the all values of listboxes that has same name?
Thank you so much in advance.
Thank you all!
I just found the answer of my problem which is getting by getting all the listboxes in web page using the following code:
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
foreach (Control control in controlCollection)
{
//if (control.GetType() == typeof(T))
if (control is T) // This is cleaner
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
Then I can get the values using the following:
int s=0;
List<ListBox> allControls = new List<ListBox>();
GetControlList<ListBox>(Page.Controls, allControls);
foreach (var childControl in allControls)
{
s += Int32.Parse( childControl.SelectedValue);
}

Is it possible to display selected items in dropdowncheckboxes text area in asp.net

In my web application, I have dropdowncheckboxes control in that whatever items I selected I need to show that selected items in dropdown textfield as separated with comma.
image description here
I tried this code but I am not getting result:
.aspx: Using this "DropDownCheckBoxes" control
<%# Register Namespace="Saplin.Controls" Assembly="DropDownCheckBoxes" TagPrefix="asp"%>
<asp:DropDownCheckBoxes ID="dropdown1" runat="server"
UseSelectAllNode="true" UseButtons="true"
OnSelectedIndexChanged="dropdown1_SelectedIndexChanged"
AutoPostBack="true" CssClass="drpdwnstyle"><Style DropDownBoxBoxWidth="200"/>
</asp:DropDownCheckBoxes>
.CS
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
List<String> checkedList = new List<string>();
foreach (ListItem item in dropdown1.Items)
{
if (item.Selected)
{
checkedList.Add(item.Text);
}
dropdown1.DataTextField = String.Join(",", checkedList);
}
}
I tried so much but I am not getting anything.
Can anyone please tell me how to do this.
Main issue is that DataTextField is not the property you want to set. This property is used together with data source, to let data bound control know which data source's field should be used as text. There is a similar field for value. Correct property to use is Texts.SelectBoxCaption, if I understood your intent correctly.
Also there is no point in assigning this inside foreach, so I moved it out of the loop:
foreach (ListItem item in dropdown1.Items)
{
if (item.Selected)
{
checkedList.Add(item.Text);
}
}
dropdown1.Texts.SelectBoxCaption = String.Join(",", checkedList);
Small correction, the following line :
dropdown1.Texts.SelectBoxCaption = String.Join(",", checkedList);
Will be replaced by :
dropdown1.Texts.SelectBoxCaption = String.Join(",", checkedList.ToArray());

Setting SelectedValue of DDL on PageLoad using value saved in Session Variable

I'm trying to set the selected value of a DropDownList on Page_Load using a value that is saved into a Session variable. The DropDownList is already populated and the value is stored along with other info in a session. I'm creating an edit entry page and want to have all of the fields already populated with the info from the Session.
What I've done is populate TextBox with the Session Variables, but for the Advisors section I need the User to enter a number instead of a name. So I need to use a DropDownList to make sure that information is entered accurately. I've looked into methods of databinding, databound, using a data source, etc but it seemed like all of those DropDownLists were generated dynamically. Any help would be much appreciated.
My .aspx Code:
<asp:TextBox runat="server" ID="fname" MaxLength="100"></asp:TextBox>
<asp:DropDownList ID="advisors" runat="server">
<asp:ListItem Value="">Select Advisor</asp:ListItem>
<asp:ListItem Value="2">Joe Schmo</asp:ListItem>
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fname.Text = Session["fname"].ToString();
lname.Text = Session["lname"].ToString();
sex.Text = Session["sex"].ToString();
sid.Text = Session["sid"].ToString();
email.Text = Session["email"].ToString();
phone.Text = Session["phone"].ToString();
advisors.SelectedValue = Session["advisor"].ToString();
}
}
UPDATE:
So I'm dumb. The Session variable was storing the name "Joe Schmo" not the Value "2". The below code worked for me.
foreach (ListItem listItem in advisors.Items)
{
listItem.Selected = listItem.Text.Equals(Session["advisor"].ToString());
}
try this
foreach (ListItem listItem in advisors.Items)
{
if(listItem.Text.Equals(Session["advisor"].ToString())
DropDownList1.Items.FindByValue(Session["advisor"].ToString()).Selected = true;
}

DropDown Selected Value not Showing up

I have drop-down inside of a gridview so when the gridview is loaded and the drop-down is bound then the drop-down only show the first value of the drop-down list and it is not showing the previously selected value. When the gridview loads, i would like the drop-down to show what was previously selected for that row. Here is my code:
aspx markup for the drop-down:
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server">
</asp:DropDownList>
</ItemTemplate>
Here is code behind:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
//get current index selected
int current_quest = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
{
con2.Open();
using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 where ID= '" + current_quest + "' ", con2))
{
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
}
con2.Close();
}
}
I have tried to add this line of code after binding but i get this error "Object reference not set to an instance of an object"
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
thanks
I believe in your SELECT you need to use current_quest_sk instead of current_quest
Aslo try to check for null before accessing your controls:
var ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
var answerLabel = e.Row.FindControl("lblAns") as Label;
if(answerLabel !=null && ddl_Answer!=null)
{
ddl_Answer.Items.FindByValue(answerLabel.Text).Selected = true;
}
#afzalulh has a valid point remove quotes if current_quest_sk(ID) is an Integer in your table.
You should avoid SQL injection but that's a different topic.
Place a breakpoint in your code, and setup through it with your debugger.
Either you have a typo in one of your string names or you are looking at the wrong control.
Stepping through your code will help you see exactly what line of your code is causing the problem.
You could also put a try/catch block around the whole thing to help you isolate the problem. Once you find the problem, remove the try/catch block.

ASP dynamic DropDownList selected index

My web form starts out as two TextBoxes, two Buttons, a CheckBoxList (bound to the results of a database query), and an empty DropDownList.
When the user enters a search phrase into the first TextBox and hits enter (or clicks the first Button, "Search"), a GridView appears, populated with rows pulled from the database. When the user hits the Select button on one of the rows, the DropDownList is populated (bound to results of a database query) and enabled (if the query returned results -- if there were no results, it remains disabled). When the second Button ("Save Settings") is clicked, the relevant data is saved to the DB, the GridView's selection is cleared, and the DropDownList is cleared and disabled.
All of the above works. The problem comes from the DropDownList. I can't get the C# code to recognize the changing SelectedIndex; depending on how I shuffle my code around, the index is always either 0 (and the DropDownList is forced to stay on the first item), or -1 (and the list becomes disabled).
DropDownList code:
<asp:DropDownList ID="myList" runat="server" AutoPostBack="True"
DataTextField="MyName" DataValueField="MyID"
Enabled="False" onselectedindexchanged="myList_SelectedIndexChanged" />
C# code:
protected void myGrid_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
if (myGrid.SelectedIndex >= 0)
{
int id = int.Parse(myGrid.Rows[myGrid.SelectedIndex].Cells[2].Text);
connection.Open();
string query = "..."; // Omitted for brevity; the query is correct
SqlDataSource source = new SqlDataSource(connectionString, query);
source.SelectParameters.Add("Param1", TypeCode.String, id.ToString());
DataTable dt = ((DataView)source.Select(DataSourceSelectArguments.Empty)).Table;
dt.AcceptChanges();
myList.DataSource = dt;
myList.DataBind();
myList.Enabled = myList.Items.Count != 0;
if (!myList.Enabled)
{
myList.Items.Add(new ListItem("No Results", "0"));
}
}
}
}
protected void myList_SelectedIndexChanged(object sender, EventArgs e)
{
// ((DropDownList)sender).SelectedIndex == -1
}
I've read that there are some problems with DropDownList while searching for a solution to my problem, but besides the note to set AutoPostBack="True", none of the other situations I've found have helped.
One common reason on why the DropDownList loses its SelectedIndex value is, that during the postback is binded again with data. Do you populate data to the DropDownList somewhere else in your code? Maybe there is something else that causes the SelectedIndex event of the GridView to fire again?
Another thought is that changing the Enabled status of the DropDownList might cause this behavior. Try your code without disabling the DropDownList, and see if something changes.

Categories

Resources