DropDown Selected Value not Showing up - c#

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.

Related

dropdown selected item and repose.redirect

I have two dropdownlist in my project and get the items from sql server. One of them show list of something (And I named it DropdownSoore) and another one show list of members of it (And I named it DropdownAye) that update when select an item from DropdownSoore. then when select an item from DropdownAye go to page of them by forwarding query string. I have no problem to updating DropdownAye but when I select item from it and redirect to page of it, the DropdownAye lose the selected item and show the first item (as default) and index to query string in url.
what should I do?
Excuse me about my grammer, I'm not English...
I set DropdownSoore:
<asp:DropDownList ID="DropDownListSoore" runat="server" class="nav-link btn btn-outline-secondary dropdown-toggle" aria-haspopup="true" aria-expanded="true" AutoPostBack="True"></asp:DropDownList>
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
string IdSoore = Convert.ToString(dt.Rows[i]["IdSoore"]);
string NameSoore = Convert.ToString(dt.Rows[i]["NameSoore"]);
DropDownListSoore.Items.Add(IdSoore + "." + NameSoore);
}
string forwardedIdSoore = Request.QueryString["IdSoore"];
if (forwardedIdSoore != null)
{
DropDownListSoore.Items.FindByValue(forwardedIdSoore);
}
And then set DropdownAye:
<asp:DropDownList ID="DropDownListAye" runat="server" class="nav-link btn btn-outline-secondary dropdown-toggle" aria-haspopup="true" aria-expanded="true" OnSelectedIndexChanged="DropDownListAye_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
DropDownListAye.Items.Clear();
for (int i = 0; i <= dt1.Rows.Count - 1; i++)
{
DropDownListAye.Items.Add(Convert.ToString(dt1.Rows[i]["NumberAye"]));
}
int iSelectedAye = Convert.ToInt32(DropDownListAye.SelectedIndex) + 1;
string SelectedAye = Convert.ToString(dt1.Rows[iSelectedAye]["IdAye"]);
Session["SSelectedAye"] = SelectedAye;
string forwardedIdAye = Request.QueryString["IdAye"];
if (forwardedIdSoore != null)
{
DropDownListSoore.Items.FindByValue(forwardedIdAye);
}
in page_Load. and dont have problem to update DopdownAye but when I used it to redirect always get IdAye=1 in url and show the first item of DropdownAye ...:
protected void DropDownListAye_SelectedIndexChanged(object sender, EventArgs e)
{
int SelectedAye = Convert.ToInt32(Session["SSelectedAye"]);
int SelectedSoore = Convert.ToInt32(DropDownListSoore.SelectedIndex) + 1;
string forward = "~/contentAye.aspx?IdSoore=" + SelectedSoore + "&IdAye=" + SelectedAye;
Response.Redirect(forward);
}
I try !IsPostBack but dont have utility too.
I do all thing I think and i dont know what shoild i do.
And where are you loading up these infomration?
Remember, page load ALWAYS fires and triggers for each post-back, for each button click, and any OTHER event on the page that calls code behind.
What does the above really mean?
Well, it means that you need to ONLY ONE TIME load up the drop downs, the gridview(s), or whatever else you have.
So, for the last 200+ web pages I have built, I ALWAYS have this code stub in the page load event:
so this markup:
<h3>Select Hotel</h3>
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField="ID"
DataTextField="HotelName" Width="356px">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="Show/get/display drop selection" OnClick="Button1_Click"
CssClass="btn" />
<br />
<h3>Selected result</h3>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
and code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// load up data, controls etc.
string strSQL =
"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
DataTable dt = General.MyRst(strSQL);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Please Select Hotel", ""));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string sResault =
$#"dropdown list value (pkid) = {DropDownList1.SelectedItem.Value}
<br/>
Dropdown list Text (Hotel) = {DropDownList1.SelectedItem.Text}";
Label1.Text = sResault;
}
and the result:
SUPER important:
If I leave out the !IsPostBack test in page load, then for EVERY button click, the dropdown list re-load code will trigger, and runs BEFORE your button stubb, or post back. As a result, I will see/find/get no valid value from the drop down list, since page load ALWAYS runs before the given code stub, and thus if page load "every time" re-loads the data, then it will blow out the choosen value in the drop down list.
So, loading up of grids, data, dropdowns etc. can ONLY occur one time in page load, since page load ALWAYS runs before each button or event code stub you have behind.
If you thus only load up the controls and dropdowns on the first REAL page load, then the values the user selects in those dropdowns should work, but only will work if you ALWAYS include that all important if (!IsPostBack) code stub in your page load event.
Now, of course in place of that button to loadup + display the dropdown list into that label?
Well, of course that button click may well (like often) jump or navigate to another page. So, in place of that code to fill out the selected value(s) into that lable, we could pass the selected value to the next page. And how to do that? Well, you can use session(), you can use parmaters in the URL, or you can even use a post-back URL, and then the WHOLE previous page becomes available (Page.Previous), which then in theory allows you to grab ANY and ALL values from the previous page.
but, say we choose session() to pass the value, then this:
Session["HotelPK"] = DropDownList1.SelectedItem.Value;
Response.Redirect("GridFun3.aspx");

dealing with GridView and Custom Validation, both client and serverside

I'm not quite sure how to solve this problem.
What I'm trying to do:
Go through a gridview with multiple rows, and force the user to enter in specific values if certain textboxes or drop down lists are left on the default value.
What I tried:
Tried client side requirements, by use of the focusout event in javascript. Focus goes onto these fields depending on the previous selections users make, that part works. My code:
var row = $(this).closest('tr');
var text = $(row).find("input[name*='txtCurriculum']").val('enter lesson/unit name here');
var ddl = $(row).find("select[name*='ddlCurrAdditions']");
$(ddl).focusout(function () {
if (ddl.val == "-select curriculum name-") {
$(ddl).focus();
alert("select a curriculum name before moving on");
}
});
$(text).focusout(function () {
if (text.val == 'enter lesson/unit name here') {
$(text).focus();
alert('enter in a lesson or unit name before moving on');
}
});
It never fired properly. the ddl focusout would fire, but wouldn't stop firing until I exited and went back to the page. the text focusout would never fire.
Tried server side validation, with the custom validation feature.
protected void cv1_ServerValidate(object source, ServerValidateEventArgs args)
{
CustomValidator cv = ((CustomValidator)(source));
GridViewRow gvr;
//if (FormCGrid.Rows)
foreach (GridViewRow row in FormCGrid.Rows)
{
//string ddl = ((DropDownList)row.FindControl("ddlCurrAdditions")).SelectedItem.Text;
string txtC = ((TextBox)row.FindControl("txtCurriculum")).Text;
bool ddl = ((DropDownList)row.FindControl("ddlCurrAdditions")).Visible;
if (txtC == "enter lesson/unit name here")
{
args.IsValid = false;
cv.ErrorMessage = string.Format("Please enter the Additional program name on row {0}", row.RowIndex);
}
else if (ddl == true)
{
cv.ErrorMessage = string.Format("Enter your lesson or unit for the curriculum selected on row {0}", row.RowIndex);
args.IsValid = false;
}
}
}
I tried to loop through the rows of the gridview here, checking the named dropdown for visibility (hidden until another dropdownlist reveals it, dependent on the value chosen there) and the textbox for the default value, yet this did not work either. It never fired at all. Any suggestions welcome.
I am generally ok with most programming/coding issues, but I find that working with the asp.net gridview, all of my techniques get thrown out the window.
Ok, there are two ways to do this, and you can use js quite easy here. However, lets go with a 100% server side code. I think sticking to server side code is easier.
Next up? I actually STONG suggest to use a listview in place of a gridview WHEN you plan to edit data. The reason is simple - the ListView does not require those "irratating" "item template" over and over for each asp.net control you want to drop/have in that grid display. Now to be fair, say 2-3 controls - then grid view is ok, but for more, then I really find that the listview starts to win here big time (no need for the item template).
The "trick" with listview is of course to setup a datasoruce on the web page, let it generate the markup, and then blow out (delete) all templates except for the item template. And then delete the datasourc1 item on the page, and remove the datasource1 setting from the list view.
However, lets go with the grid view - this will thus be some what "more messy"
So, we going to fill out the grid - and say we want a city combo box - MUST be selected. And lets toss in a basic check for say LastName also must be entered.
So, we have a city combo box (database driven). And say lets toss in a drop down for a hotel rating (1-5) - but that's only 5 choices - so we have that dropdown with the list in mark-up. (so two combo examples to show how this works).
So, say we have a grid like this, and we hit save, we get this result:
Now, of course we would fancy up that message box area. And in fact, we could VERY easy drop in jQuery.UI and make that cute div on the right appear in a dialog box (and we can trigger that box + jQuery.UI dialog display even from our server side code behind - but lets try and keep this short - but I would fancy up that error message area).
Ok, first the markup:
Just a simple grid, but "a bit messy" due to those "item Templates - (if you not figured this out, I really dislike those template things!!! - and with listview you don't need them!! - just drop in pure clean asp.net controls for the grid). Anyway:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:TemplateField HeaderText="HotelName" >
<ItemTemplate><asp:TextBox id="HotelName" runat="server" Text='<%# Eval("HotelName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" >
<ItemTemplate><asp:TextBox id="FirstName" runat="server" Text='<%# Eval("FirstName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" >
<ItemTemplate><asp:TextBox id="LastName" runat="server" Text='<%# Eval("LastName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" DataTextField="City"
DataValueField = "City" Width="110px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active">
<ItemTemplate><asp:CheckBox id="Active" runat="server" Checked = '<%# Eval("Active") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:DropDownList ID="cboRating" runat="server" SelectedValue = '<%# Eval("Rating") %>' >
<asp:ListItem Value="1">Poor</asp:ListItem>
<asp:ListItem Value="2">Just Ok</asp:ListItem>
<asp:ListItem Value="3">Ok</asp:ListItem>
<asp:ListItem Value="4">Good</asp:ListItem>
<asp:ListItem Value="5">Excellent</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="ErrorDialog" style="display:normal;float:left;padding-left:30px;width:20%" runat="server">
<asp:TextBox ID="txtErrors" runat="server" TextMode="MultiLine" Style="width:100%" Rows="20" ></asp:TextBox>
</div>
<div style="clear:both;padding-top:20px">
<asp:Button ID="cmdSave" runat="server" Text="Save" />
<asp:Button ID="cmdUnDo" runat="server" Text="UnDo" Style="margin-left:20px"/>
</div>
Ok, now on SO? Gee, that is about the total max markup I would post in one shot - beyond above, we approach the "not very nice" post territory.
Ok, so lets look at the code to load up this grid. We have this code:
public class EditHotelsG : System.Web.UI.Page
{
private DataTable rstTable = new DataTable();
private DataTable rstCity = new DataTable();
protected void Page_Load(object sender, System.EventArgs e)
{
if (System.Web.UI.Page.IsPostBack == false)
{
ErrorDialog.Visible = false;
LoadGrid();
ViewState["rstTable"] = rstTable;
ViewState["rstCity"] = rstCity;
}
else
{
rstTable = ViewState["rstTable"];
rstCity = ViewState["rstCity"];
}
}
public void LoadGrid()
{
// load up our drop down list from database (city)
string strSQL;
strSQL = "SELECT City from tblCity Order by City";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
rstCity.Load(cmdSQL.ExecuteReader);
// now load up main grid view
strSQL = "SELECT ID, FirstName, LastName, HotelName, City, Active, Rating from tblHotels ORDER BY HotelName";
cmdSQL.CommandText = strSQL;
rstTable.Load(cmdSQL.ExecuteReader);
GridView1.DataSource = rstTable;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// set combo box data source
if (e.Row.RowType == DataControlRowType.DataRow)
{
// setup city drop down list
DropDownList cboDrop = e.Row.FindControl("cboCity");
cboDrop.DataSource = rstCity;
cboDrop.DataBind();
cboDrop.Items.Insert(0, new ListItem(string.Empty)); // add blank row
cboDrop.Text = rstTable.Rows(e.Row.RowIndex).Item("City").ToString;
}
}
}
Ok, now that is not all that much code. And a good part was setting up that combo box. Since the cbo box (dropdown list) was database driven, then we have to bind + setup for each row. So, that cost us a good chunk of our coding time.
Note however how we persist the database soruce (table). We do that, since we want to with A LOT LESS code, update the whole database behind in ONE shot. By peristing that table, then we
Transfer data from Grid to table
Save the table to database in one shot
So, this reduces our coding efforts by a truckload.
The code to save our data, thus becomes this gem:
(and note how we ALSO put in our validation code).
protected void cmdSave_Click(object sender, EventArgs e)
{
// pull gride rows back to table.
bool bolDataOk = true;
txtErrors.Text = "";
foreach (GridViewRow rRow in GridView1.Rows)
{
int RecordPtr = rRow.RowIndex;
DataRow OneDataRow;
OneDataRow = rstTable.Rows(RecordPtr);
OneDataRow.Item("HotelName") = rRow.FindControl("HotelName") as TextBox.Text;
OneDataRow.Item("FirstName") = rRow.FindControl("FirstName") as TextBox.Text;
OneDataRow.Item("LastName") = rRow.FindControl("LastName") as TextBox.Text;
OneDataRow.Item("City") = rRow.FindControl("cboCity") as DropDownList.Text;
OneDataRow.Item("Active") = rRow.FindControl("Active") as CheckBox.Checked;
OneDataRow.Item("Rating") = rRow.FindControl("cboRating") as DropDownList.SelectedValue;
// check for missing City, or LastName
if (IsDBNull(OneDataRow("City")) | OneDataRow("City") == "")
{
bolDataOk = false;
if (txtErrors.Text != "")
txtErrors.Text += Constants.vbCrLf;
txtErrors.Text += "Missing City on row = " + (rRow.RowIndex + 1).ToString;
}
if (IsDBNull(OneDataRow("LastName")) | OneDataRow("LastName") == "")
{
bolDataOk = false;
if (txtErrors.Text != "")
txtErrors.Text += Constants.vbCrLf;
txtErrors.Text += "Missing lastName on row = " + (rRow.RowIndex + 1).ToString;
}
}
ErrorDialog.Visible = !(bolDataOk);
// now send table back to database with updates
if (bolDataOk)
{
string strSQL = "SELECT ID, FirstName, LastName, City, HotelName, Active, Rating from tblHotels WHERE ID = 0";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daupdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder cmdBuild = new SqlCommandBuilder(daupdate);
daupdate.Update(rstTable);
}
}
}
Now, once again, that above code snip is a wee bit long - and is aobut the max size of a code snip for SO. I would perhaps consider breaking out that above last code into 2 or even 3 routines.
but, all in all, the above shows quite a few tricks, and approaches here.
As noted, I was going to post how you can/could verify using client side code, ,but the OVER ALL idea of saving back the whole grid with one database update? Well, I would use that trick with a listview, gridview, and even if I was doing client side js verification? I will still use the bulk of the above design pattern.
And the un-do button? Well, I never finished that part - but it would just call the same code as the first page load (postback - false, and you would simply re-bind the grid from the database source for the un-do button.

How preserve the values accessing dynamic controls

Hello everybody and thanks in advance,
I´ve read several threads about but I'm very confused. The thing is I'm dynamically creating some textboxes inside a panel control which is placed inside a formview whith this code...
protected void Muestra_Precio_Stock_BT_Click(object sender, EventArgs e)
{
CheckBoxList FormatosCL = (CheckBoxList)FormViewDiscos.FindControl("FormatosCL");
Panel Precio_Stock_PN = (Panel)FormViewDiscos.FindControl("CB_Precio_Stock_PN");
Label NuevoPrecioLB = null;
TextBox NuevoPrecioTB = null;
Label NuevoStockLB = null;
TextBox NuevoStockTB = null;
foreach (ListItem item in FormatosCL.Items)
{
if(item.Selected)
{
NuevoPrecioLB = new Label();
NuevoPrecioTB = new TextBox();
NuevoStockLB = new Label();
NuevoStockTB = new TextBox();
NuevoPrecioLB.ID = "NuevoPrecioLB_" + FormatosCL.Items.IndexOf(item);
NuevoPrecioLB.Text = "PRECIO " + item.Text + ": ";
NuevoPrecioTB.ID = "NuevoPrecioTB_" + FormatosCL.Items.IndexOf(item);
NuevoStockLB.ID = "NuevoStockLB_" + FormatosCL.Items.IndexOf(item);
NuevoStockLB.Text = " STOCK " + item.Text + ": ";
NuevoStockTB.ID = "NuevoStockTB_" + FormatosCL.Items.IndexOf(item);
Precio_Stock_PN.Controls.Add(NuevoPrecioLB);
Precio_Stock_PN.Controls.Add(NuevoPrecioTB);
Precio_Stock_PN.Controls.Add(NuevoStockLB);
Precio_Stock_PN.Controls.Add(NuevoStockTB);
Precio_Stock_PN.Controls.Add(new LiteralControl("<br />"));
}
}
}
Well, this works well, when I run the project the textboxes and labels are created as expected, I can see them and write into the textboxes. I`ve put the same code into Page_Load event and now I can get the created controls and avoid the nullpointerexception (that was my first problem) when I click the INSERT button of the formview. The problem is that, in the following code...
protected void InsertButton_Click(object sender, EventArgs e)
{
TextBox DiscIdTB = (TextBox)FormViewDiscos.FindControl("DiscIdTB");
TextBox CaratulaTB = (TextBox)FormViewDiscos.FindControl("CaratulaTB");
CheckBoxList CancionesCL = (CheckBoxList)FormViewDiscos.FindControl("CancionesCL");
CheckBoxList FormatosCL = (CheckBoxList)FormViewDiscos.FindControl("FormatosCL");
using (SqlConnection conexion = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBBDD-Discos"].ConnectionString))
{
conexion.Open();
cmd.Connection = conexion;
cmd.CommandText = "INSERT INTO DISCOS_FORMATOS (ID_DISCO, ID_FORMATO, PRECIO, STOCK) VALUES ((SELECT MAX(ID_DISCO) FROM DISCOS), #IdFormato, 0, 0)";
foreach (ListItem item in FormatosCL.Items)
{
if (item.Selected)
{
Panel Precio_Stock_PN = (Panel)FormViewDiscos.FindControl("CB_Precio_Stock_PN");
string control = "NuevoPrecioTB_" + (FormatosCL.Items.IndexOf(item));
string control2 = "NuevoStockTB_" + (FormatosCL.Items.IndexOf(item));
TextBox Precio = (TextBox)Precio_Stock_PN.FindControl(control);
TextBox Stock = (TextBox)Precio_Stock_PN.FindControl(control2);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IdFormato", item.Value);
cmd.Parameters.AddWithValue("#IdPrecio", Convert.ToInt32(Precio.Text));
cmd.Parameters.AddWithValue("#IdStock", Convert.ToInt32(Stock.Text));
cmd.ExecuteNonQuery();
}
}
conexion.Close();
cmd.Dispose();
}
}
when the execution reaches these lines, dynamically created textboxes lost their values, returning always 0...
cmd.Parameters.AddWithValue("#IdPrecio", Convert.ToInt32(Precio.Text));
cmd.Parameters.AddWithValue("#IdStock", Convert.ToInt32(Stock.Text));
How can I preserve their user typed values?
Have you tried putting the code in the Page_Load method inside a block with
if (!IsPostBack)
{
//
}
Another thing you can try if this doesn't work is saving the typed-in values in Session variables.
I don't think the InsertButton is important here. By the way, if you use the runat=server on the objects you don't have to use FindControl, the server will be able to manage it. Also for dynamic controls you might want to try a different approach like: GridView (remove headers and it won't look like a grid), a DataList, or a ListView. What goes inside the ItemTemplate are the objects you are repeating/creating dynamically. You can add labels and textboxes here. For example:
<asp:ListView ID="repeatedStuff" runat="server"><ItemTemplate>
</ItemTemplate>
</asp:ListView>
Or
<asp:DataListID="list"
CellPadding="2"
RepeatDirection="Vertical"
RepeatLayout="Table"
RepeatColumns="2"
runat="server">
<ItemTemplate>
<asp:CheckBoxID="cboxP"AutoPostBack="True"runat="server"/>
<asp:Labelrunat="server"Text='<%#Bind("Nombre")%>'ID='<%#Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:DataList>
What remains after this approach is managing the binding and how to identify them when an event is triggered. Like adding a textchange event on server side, if you bind the ID value on the event you ask for the sender's ID and then you can know which one is being "textchanged".

Dropdown only returns item text/value from first item

EDIT: So I found that this line listItem.Value = rdr["lvl"].ToString(); was adding the same value for each item in the dropdown. Since each text item had the same value, I guess it always defaulted to the first text item. I'm now passing lvl through another query instead of the dropdown. Thanks for all the helpful input!
I'm trying to accomplish a pretty simple task which I've done numerous times before. For some reason, I can't get my dropdown to correctly pass the SelectedItem and SelectedValue.
The SelectedItem and SelectedValue are always returned for the first item in the dropdown, regardless of which item I select.
What am I doing wrong?
Defining dropdown and button:
<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Populating dropdown on PageLoad:
myConnection.Open();
SqlCommand rpt = new SqlCommand(getreports, myConnection);
SqlDataReader rdr = rpt.ExecuteReader();
if (!Page.IsPostBack)
{
while (rdr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = rdr["manager"].ToString();
listItem.Value = rdr["lvl"].ToString();
DropDownList1.Items.Add(listItem);
}
rdr.Close();
myConnection.Close();
}
Code for button click that should pass SelectedItem and SelectedValue:
protected void Button1_Click(object sender, EventArgs e)
{
string user = DropDownList1.SelectedItem.Text;
string lvl = DropDownList1.SelectedValue;
Label1.Text = user;
Label2.Text = lvl;
}
I realized the same value was being assigned for each item. This was the reason the first item in the dropdown kept being passed regardless of the selection. As long as the values are different, all the above code works as expected.

Cant View CheckBoxList from the database

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).

Categories

Resources