I am attempting to check all/specific checkboxes within a checkboxlist on pageload.
Currently there are no errors however even with Selected=true specified in the code behind, the checkboxes are displaying 'unticked'.
Here is my Code behind: (note: it is located within the Protected Void Page_Load and within if (!IsPostBack)
SqlConnection aircraftCheckConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CamoDatabaseString"].ToString());
SqlCommand aircraftCheckCommand = new SqlCommand("SELECT [Type] FROM [AircraftType]");
aircraftCheckCommand.Connection = aircraftCheckConn;
aircraftCheckConn.Open();
SqlDataAdapter aircraftCheckAdapt = new SqlDataAdapter(aircraftCheckCommand);
DataSet AircraftDS = new DataSet();
aircraftCheckAdapt.Fill(AircraftDS);
AircraftCheck.DataSource = AircraftDS;
AircraftCheck.DataTextField = "Type";
AircraftCheck.DataValueField = "Type";
aircraftCheckConn.Close();
AircraftCheck.DataBind();
foreach (ListItem li in AircraftCheck.Items)
{
li.Selected = true;
}
AircraftCheck.DataBind();
Here is my front-end
<asp:CheckBoxList ID="AircraftCheck" runat="server" DataTextField="Type" DataValueField="Type" CellSpacing="10" RepeatColumns="6" RepeatDirection="Horizontal" >
</asp:CheckBoxList>
Thanks
Based from page life cycle, the Page_Load event called before binding of CheckBoxList items occur. You can replicate same code from Page_Load event in CheckBoxList's DataBound event method and put OnDataBound handler on CheckBoxList markup to corresponding method:
ASPX Markup
<asp:CheckBoxList ID="AircraftCheck" runat="server" DataTextField="Type" DataValueField="Type" CellSpacing="10" RepeatColumns="6" RepeatDirection="Horizontal"
OnDataBound="AircraftCheck_DataBound">
</asp:CheckBoxList>
Code Behind
protected void AircraftCheck_DataBound(object sender, EventArgs e)
{
// SqlConnection binding stuff here, omitted for brevity
AircraftCheck.DataBind();
foreach (ListItem li in AircraftCheck.Items)
{
li.Selected = true;
}
}
Similar issue:
How to check all checkboxes in a checkboxlist when page first loads?
Related
I have a Table dynamically generated and inside of 2 columns there are TextBoxes. During the postback the Textboxes are always empty even if I fill them.
The table is builted in this way:
protected void ddlScalaTaglie_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtRighe = oTab.getScaleTaglieRighe(ddlScalaTaglie.SelectedValue);
//dt is datatable object which holds DB results.
Table tbl = new Table();
tbl.CssClass = "table table-striped table-bordered table-responsive";
TableRow tr;
TableCell tcEU, tcUS, tcUK, tcQty, tcEAN;
Label lbEU, lbUS, lbUK, lbQty, lbEAN;
TextBox tbEU, tbUS, tbUK, tbQty, tbEAN, tbToFocus = null;
foreach (DataRow dr in dtRighe.Rows)
{
tr = new TableRow();
//ean
tcEAN = new TableCell();
tbEAN = new TextBox();
tbEAN.ID = "txtEAN" + dr[0].ToString();
tbEAN.Width = new Unit(100, UnitType.Percentage);
tbEAN.Columns = 15;
tcEAN.Controls.Add(tbEAN);
tr.Controls.Add(tcEAN);
//Qty
tcQty = new TableCell();
tbQty = new TextBox();
tbQty.ID = "txtQty" + dr[0].ToString();
tbQty.TextMode = TextBoxMode.Number;
tcQty.Controls.Add(tbQty);
tr.Controls.Add(tcQty);
tbl.Controls.Add(tr);
}
Session["tbl"] = tbl;
divTaglieRighe.Controls.Add(tbl);
}
When I click the button SAVE, I have to loop throug my table and save all the TextBox.Text...
this is what I wrote:
ArrayList arrScarpaFigli = new ArrayList();
Table tbl = (Table)Session["tbl"];
foreach (TableRow row in tbl.Rows)
{
foreach (TableCell cell in row.Cells)
{
foreach (Control ctrl in cell.Controls)
{
//CONTROL IS TEXBOXT: EXTRACT VALUES//
if (ctrl is TextBox)
{
TextBox txt = (TextBox)ctrl;
arrScarpaFigli.Add(txt.Text);
}
}
}
}
The problem is that, also if I fill the textboxes, in my Text there is always an empty string.
The only moment when I fill the table is on the selectionChange of a Dropdown.
What I'm doing wrong?
Thanks in advance
You have to recreate dynamic controls on every page load to make sure their values are retained after a PostBack. So you need to create a new Method that handles the creation of the Table every time the page is loaded.
protected void Page_Load(object sender, EventArgs e)
{
//always create the controls on every page load if there is a value selected in ddlScalaTaglie
if (!string.IsNullOrEmpty(ddlScalaTaglie.SelectedValue))
{
createTable(ddlScalaTaglie.SelectedValue);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//use findcontrol to find the Table inside the placeholder
Table tbl = Page.FindControl("divTaglieRighe").FindControl("Table1") as Table;
//loop all rows and cells in the Table
foreach (TableRow row in tbl.Rows)
{
foreach (TableCell cell in row.Cells)
{
foreach (Control ctrl in cell.Controls)
{
//the control is a textbox
if (ctrl is TextBox)
{
//cast the control back to a textbox
TextBox tb = ctrl as TextBox;
//does the checkbox have a value, if so append the label
if (!string.IsNullOrEmpty(tb.Text))
{
Label1.Text += tb.Text + "<br>";
}
}
}
}
}
}
protected void ddlScalaTaglie_SelectedIndexChanged(object sender, EventArgs e)
{
//no need to create the Table dynamically, that will be handled in Page_Load
//this method is just a dummy to trigger a PostBack
//you could remove this method and the OnSelectedIndexChanged from the DropDown
//and just keep the AutoPostBack="true", that will also work
}
private void createTable(string value)
{
DataTable dtRighe = Common.LoadFromDB();
//create a new table WITH id, that is needed for findcontrol
Table tbl = new Table();
tbl.ID = "Table1";
//loop all rows in the datatable
foreach (DataRow dr in dtRighe.Rows)
{
TableRow tr = new TableRow();
//ean
TableCell tcEAN = new TableCell();
TextBox tbEAN = new TextBox();
tbEAN.ID = "txtEAN" + dr[0].ToString();
tbEAN.Width = new Unit(100, UnitType.Percentage);
tbEAN.Columns = 15;
tcEAN.Controls.Add(tbEAN);
tr.Controls.Add(tcEAN);
//Qty
TableCell tcQty = new TableCell();
TextBox tbQty = new TextBox();
tbQty.ID = "txtQty" + dr[0].ToString();
tbQty.TextMode = TextBoxMode.Number;
tcQty.Controls.Add(tbQty);
tr.Controls.Add(tcQty);
tbl.Controls.Add(tr);
}
//add the table to the placeholder
divTaglieRighe.Controls.Add(tbl);
}
The aspx to make the example complete
<asp:DropDownList ID="ddlScalaTaglie" runat="server" OnSelectedIndexChanged="ddlScalaTaglie_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="Select..." Value=""></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:PlaceHolder ID="divTaglieRighe" runat="server"></asp:PlaceHolder>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
Storing an instance of Table control in Session is a terrible idea and is just plain wrong. Controls belong to their parent page - they should be added to it as soon as they are created and they should die with their parent page.
The thing with dynamically created controls in ASP.NET is that you have to store an indicator of the fact that they were created (together with relevant information needed to create them again) and recreate them on all subsequent postbacks - no later than in Page_Load. Only then these controls will have the chance of getting their values from Request and you will have the chance of obtaining these values from controls.
In your code, the instance of Table stored in Session (together with all its rows, cells and textboxes) will never reflect any client-side data changes, nor will it belong to Pages that will be created to process subsequent postback requests.
Update
The important fact to understand here is that, after processing the postback caused by ddlScalaTaglie change and returning hew html to the client, the page instance is gone. On next request a new instance of your page is created - and it does not know anything about the fact that the previous instance had table added to its control tree. It is your code in Page_Load that must discover that the form must have this table, and create the table in exactly the same way it was created the first time - with rows, cells and textboxes with exactly the same IDs.
Then, after you add this newly created table to divTaglieRighe.Controls, the textboxes will be able to extract their client-side values from Request.Form collection.
Make sure the textbox has a "name" for the post back to the controller.
If it does not it grabs a null for the parameter.
Check Request.Form for data returned to controller.
You've created a Table called tbl and added two TextBox, then you store Table control in session Session["tbl"] and added to divTaglieRighe control. Finally you are trying to get TextBox data from your session Session["tbl"] table not the ViewState control that added in divTaglieRighe control. You have to get data from you Table tbl control that added in divTaglieRighe control.
At the moment i have a method that retrieves a list of name from my database and return as an arraylist.
public static ArrayList GenerateFolderLocation(String username)
{
// Get User ID
SqlDataReader sqlUserID = GetUserInformation(username);
sqlUserID.Read();
int userid = int.Parse(sqlUserID["userid"].ToString());
SqlCommand cmd = new SqlCommand("SELECT distinct foldername FROM mb_folder WHERE userid=#userid", SQLGetMBoxConnection());
cmd.Parameters.AddWithValue("#userid", userid);
SqlDataReader sqldr = cmd.ExecuteReader();
ArrayList locationList = new ArrayList();
while (sqldr.Read())
{
locationList.Add(sqldr["foldername"].ToString());
}
locationList.Sort();
return locationList;
}
And in my page load method, i use DataSource and DataBind to fill up a dropdownlist i have on my main page. Note UploadLocation is the id of my dropdownlist
UploadLocation.DataSource= MBFolder.GenerateFolderLocation(Context.User.Identity.Name);
UploadLocation.DataBind();
And in my main page i have this dropdownlist and i also have a submit button
<asp:DropDownList ID="UploadLocation" runat="server"
AutoEventWireup="true" EnableViewState="true">
</asp:DropDownList>
<asp:Button ID="NewUploadFile" runat="server" Text="Upload" OnClick="NewUploadFile_Click" ValidationGroup="UploadFileValidation" AutoPostBack="true"/>
What my problem is that when i click my submit button it fires the "NewUploadFile_Click" and in that method i want to retrieve the selected value of my dropdownlist. However right now i am able to retrieve the value but it is the first value in my dropdownlist. So for example, in my arraylist there would be (test1,test2,test3) and if i select "test2" my method would retrieve "test1" instead.
In "NewUploadFile_click" i use UploadLocation.SelectedItem.Text; to get the selected value. What am i doing wrong? How can i retrieve the selected data. Thx
Try wrapping your list initialisation code within an !IsPostBack {} section in the PageLoad Event.
ie in Page_Load
if (!IsPostback)
{
... Initialise List here
}
Looks like you may be rebinding the list before you have got the data you need.
When you are calling a method to bind dropdownlist, try to add it inside
In PageLoad event:
if(!IsPostBack)
{
fillvalues();
}
So, It will not fire everytime you change your selections
Try setting AutoPostBack="true"; into your DropDownList
<asp:DropDownList ID="UploadLocation" runat="server"
AutoEventWireup="true" EnableViewState="true" AutoPostBack="true";>
</asp:DropDownList>
Confirm that you page level ViewState is enabled
and also confirm that your databinding code is inside !IsPostback condition
if (!IsPostback)
{
.... databinding code..
}
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.
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;
}
188 Points
400 Posts
Dynamic Formview with a dropdown list fails horribly.
6 hours, 21 minutes ago|LINK
I've got concept in my head that I'm trying to materialize and it's not working. Here is what needs to happen: User selects a item from a list. Based on the selection a formview is built dynamically. The formview needs to be dynamic because the query will return a dataset with null values among non-null values such as this:
4600, 1, 4, NULL, NULL, 68 ....
The "4600" is model number and everything else is a ID that corresponds to a component. The Null values means that this filed does not belong to the 4600.
Henceforth, the formview then is build such that "4600" is fed to a label. For each non-null value I need to build a dropdown list, each with a separate datascource, not the ODS stuff, but a call to BLL class. Then the non-null value is assigned to the ddl's selected value property.
Simple enough, no? So here is the code and it's failing horribly. Actually just times out in an infinite loop. The time out happens in the ddlTonerBlack_DataBinding method. Can someone tell me what I'm doing wrong? Thanks. EJM
aspx markup:
<form id="form1" runat="server">
<div>
<asp:DropDownList runat="server" ID="ddlPrinterModels" AppendDataBoundItems="True"
DataTextField="Hardware_Model" DataValueField="Hardware_Model"
width="246px" CssClass="AssetMngnt-smallFont" AutoPostBack="true" >
<asp:ListItem Value="-1" Selected="True">-- Select Printer Model --</asp:ListItem>
</asp:DropDownList>
<hr />
<asp:PlaceHolder id="DetailsViewPlaceHolder" runat="server"/>
</div>
<!-- NOT A COMPLETE QUERY -->
<asp:sqldatasource id="ODSTonerBlackByModel"
selectcommand="SELECT [Hardware_Model], [Ident_Black], [Ident_Cyan], [Ident_Yellow] FROM [cPrinters_Toners] WHERE ([Hardware_Model] = #Hardware_Model)"
connectionstring="<%$ ConnectionStrings:CISF_Asset_Management %>"
runat="server">
<SelectParameters>
<asp:ControlParameter ControlID="ddlPrinterModels" Name="Hardware_Model"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</form>
Now the code file:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData_PrinterModels();
}
FormView printerModelFormView = new FormView();
dalConsumables_TonerBlack x = new dalConsumables_TonerBlack();
printerModelFormView.ID = "fvPrinterModel";
printerModelFormView.DataSourceID = "ODSTonerBlackByModel";
printerModelFormView.PagerSettings.Mode = PagerButtons.NextPrevious;
printerModelFormView.HeaderText = "Printer Model";
printerModelFormView.ItemTemplate = new FormViewTemplate();
DetailsViewPlaceHolder.Controls.Add(printerModelFormView);
}
protected void LoadData_PrinterModels()
{
Printer_ModelsList x = new Printer_ModelsList();
ddlPrinterModels.DataSource = x.GetPrinetr_Models();
ddlPrinterModels.DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
SqlDataSource sqlDS = new SqlDataSource();
sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings["CISF_Asset_Management"].ConnectionString;
sqlDS.SelectCommand = "SELECT dbo.cCartridge_Black.Ident_Black, dbo.cCartridge_Black.Model_Black, " +
"dbo.cCartridge_Black.Desc_Black, dbo.cCartridge_Black.Qty_Black, " +
"dbo.cCartridge_Black.Black_Reorder_Limit, dbo.cCartridge_Black.Notes, " +
"dbo.cCartridge_Black.UpdatedBy, dbo.cPrinters_Toners.Hardware_Model " +
"FROM dbo.cCartridge_Black LEFT OUTER JOIN " +
"dbo.cPrinters_Toners ON dbo.cCartridge_Black.Ident_Black " +
"= dbo.cPrinters_Toners.Ident_Black";
form1.Controls.Add(sqlDS);
DropDownList ddl = new DropDownList();
ddl.ID = "ddlTonerBlack";
ddl.DataSource = sqlDS;
ddl.DataTextField = "Model_Black";
ddl.DataValueField = "Ident_Black";
form1.Controls.Add(ddl);
}
}
And the template class:
public class FormViewTemplate : System.Web.UI.ITemplate
{
void System.Web.UI.ITemplate.InstantiateIn(System.Web.UI.Control container)
{
Label lblPrinterModel = new Label();
lblPrinterModel.ID = "lblHardwareModel";
lblPrinterModel.DataBinding += new EventHandler(PrinterModelLabel_DataBinding);
container.Controls.Add(lblPrinterModel);
DropDownList ddlTonerBlack = new DropDownList();
ddlTonerBlack.ID = "ddlTonerBlack";
ddlTonerBlack.DataBinding +=new EventHandler(ddlTonerBlack_DataBinding);
container.Controls.Add(ddlTonerBlack);
}
private void PrinterModelLabel_DataBinding(Object sender, EventArgs e)
{
Label lblPrinterModel = (Label)sender;
FormView formViewContainer = (FormView)lblPrinterModel.NamingContainer;
DataRowView rowView = (DataRowView)formViewContainer.DataItem;
lblPrinterModel.Text = rowView["Hardware_Model"].ToString();
}
private void ddlTonerBlack_DataBinding(Object sender, EventArgs e)
{
DropDownList ddlTonerBlack = (DropDownList)sender;
FormView formViewContainer = (FormView)ddlTonerBlack.NamingContainer;
DataRowView rowView = (DataRowView)formViewContainer.DataItem;
dalConsumables_TonerBlack x = new dalConsumables_TonerBlack();
ddlTonerBlack.DataSource = x.GetListTonersBlack();
ddlTonerBlack.DataBind();
ddlTonerBlack.SelectedValue = rowView["Ident_Black"].ToString();
}
}
You get an infinite loop because in ddlTonerBlack_DataBinding method you call a DataBind method on the control that just fired a data bind event.
Simply you cause a databind event to fire in databind event handler of the same control and that's why you get an infinite loop.