HtmlInputCheckBox in Repeater always not checked - c#

i'm using a HtmlInputCheckBox in a repeater by adding
<input id="CheckBox1" type="checkbox" runat="server" value='<%# Eval ("userid") %>' />
to repeater->ItemTemplate->table->tr->td and in the server side i'm using
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < UserRepeater.Items.Count; i++)
{
var chkBox = UserRepeater.Items[i].FindControl("CheckBox1") as HtmlInputCheckBox;
if (chkBox != null && chkBox.Checked)
{
//
}
}
}
i'm not programatically setting any checkbox to set - i'm checking them on the web page during test.
my var checkbox is always inchecked {Value = "1,2,3,4" Checked = false}, thx for helping me with that.

How are you populating your repeater - if you are doing it in page_load make sure it is protected for postbacks:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// populate your data
}
}
EDIT
This is assuming you are working with viewstate on - which is the case by default.

This may be to do with when you bind your repeater. If you are binding on Page_Load, the check boxes will be created after viewstate and post variables have been restored, so the value won't be on your checkboxes.
If possible, move the data bind to Page_Init; as this happens before viewstate/post values are restored your checkboxes will get the right values assigned. If you can't bind on Page_Init, then #Aristos's answer will do.

Related

How do you get POSTed value from dynamically populated dropdownlist without the use of UpdatePanel?

I have a Web Form dependent on a Master Page, that contains a simple Form like this:
<asp:TextBox runat="server" ID="txtValue"></asp:TextBox>
<asp:DropDownList runat="server" ID="ddlProduct" />
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_OnClick" />
on Page_Load I dynamically populate the DropDownList with values:
foreach(var product in products)
{
ListItem item = new ListItem(product.Nazev, product.ProductId.ToString());
ddlProduct.Items.Add(item);
}
Now .. normally if the DropDownList was populated statically, I would go with this, to get my selected value out of it:
protected void btnConfirm_OnClick(object sender, EventArgs e)
{
string selectedProduct = ddlProduct.SelectedValue;
}
But this is a no-go in this situation. Hence I try to directly get the selected value from POSTed parameters with one of those approaches (which are in fact practically the same):
protected void btnConfirm_OnClick(object sender, EventArgs e)
{
string selectedProduct = Request.Form.Get(ddlProdukt.ClientID);
string selectedProduct2 = Request.Params[ddlProdukt.ClientID];
}
But it doesn't work. If I debug it, the actual "id/name" of the DropDownList in the POSTed Form (Request.Params) is:
"ctl00$MainContent$ddlProdukt"
whereas the ClientId my approach gives me is:
"ctl00_MainContent_ddlProdukt"
I can't figure out, why does it replace '_' for '$' in the ID of my DDL control.. It seems to be such a trivial thing. There should be a better way to find out the right ID, than replacing the character, right?
Is there some other way I should "look/ask" for the selected value?
*Take into account, that I'am not looking for a solution with an UpdatePanel. I know, that using an UpdatePanel would result in the DDL value being sucessfully selected after the Postback, but that is NOT the answer I'm looking for here.
Thank you for any input.
If you still need to use the Request.Form.Get or Request.Params you should call it on ddlProdukt.UniqueID as it's separator is '$' versus '_' on the .ClientID
As requested an example. This code and the <asp:DropDownList ID="ddlProduct" runat="server"></asp:DropDownList> are on the aspx page, not the Master.
protected void Page_Load(object sender, EventArgs e)
{
//bind data not here
if (IsPostBack == false)
{
//but inside the ispostback check
ddlProduct.Items.Add(new ListItem("Item 1", "1"));
ddlProduct.Items.Add(new ListItem("Item 2", "2"));
ddlProduct.Items.Add(new ListItem("Item 3", "3"));
ddlProduct.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = ddlProduct.SelectedValue;
}

ASPxGridView allow sorting and DataItemTemplate with ASPxCheckBox

I have an ASPxGridView that contains a column with a DataItemTemplate that contains an ASPxCheckBox. I then have a button outside of the grid that performs some actions based on whether the checkbox is checked.
The grid is defined as:
<dx:ASPxGridView ID="grid" runat="server">
<Columns>
<dx:GridViewDataColumn>
<DataItemTemplate>
<ds:ASPxCheckBox ID="checkbox" runat="server" />
</DataItemTemplate>
</dx:GridViewDataColumn>
<Columns>
</dx:ASPxGridView>
The grid is populated in Page_Load as such:
protected void Page_Load(object sender, EventArgs e)
{
//Some stuff
grid.DataSource = sourceTable;
grid.DataBind();
//Other stuff
}
Where sourceTable is defined as:
public DataTable sourceTable
{
get
{
if (ViewState["sourceTable"] == null)
return new DataTable();
return (DataTable)ViewState["sourceTable"];
}
set
{
ViewState["sourceTable"] = value;
}
}
And populated elsewhere. (The population is not important and works)
The code is implemented as such to ensure that sorting and paging works correctly on the grid, as defined in various DevExpress support topics. This is understandable. However, when we try to get the Checked value from checkbox on the button click, it is always false:
protected void button_Click(object sender, EventArgs e)
{
//Some stuff
for(int i = 0; i < grid.VisibleRowCount; i++)
{
//Other stuff
ASPxCheckBox checkbox = grid.FindRowCellTemplateControl(i, grid.Columns[0], "checkbox") as ASPxCheckBox;
if(checkbox.Checked) //Always false
{
//Do conditional stuff
}
//More stuff
}
//Even more stuff
}
I understand why this is always false as the grid rebinds the data and recreates the checkbox to its default state, any documentation I have found for this issue regarding DevExpress states to wrap the data binding in Page_Load in if(!Page.IsPostBack) which does indeed work, but breaks sorting and paging.
I'm sure I have the solution for this in other projects I have done, I just can't find it. What should be done in this case?
Note: I have shortened the code to as little as I can possibly get away with and have not tested it. There may be some small errors with the actual code, but use it as a guide to what I am trying to do and will clarify any issues people may come across.
EDIT: Using if(!Page.IsPostBack) or if(!Page.IsCallback) in Page_Load stops sorting and paging on the grid, removing this condition means Checked is always false. I need both sorting/paging to occur AND to be able to read the Checked value of the ASPxCheckBox in the DataItemTemplate.
Edited answer
It appears that when using editors in DataItemTemplate you have to use LoadPostData() to get their values.
Use:
for(int i = 0; i < grid.VisibleRowCount; i++)
{
ASPxCheckBox checkbox = grid.FindRowCellTemplateControl(i, grid.Columns[0], "checkbox") as ASPxCheckBox;
((IPostBackDataHandler)checkbox).LoadPostData(checkbox.UniqueID, Request.Form);
if(checkbox.Checked)
{
//Do conditional stuff
}
}
As for populating the grid, you can keep it inside the Page_Load without !IsPostBack because it does not affect the editors (and it will keep the filtering/sorting)
It can cause problems in other cases but this is not the case here.
Hope it helps! Please tell me if you have any questions
Because when you button click then page post to server and when page posting to server all control set to default value (If you don`t control isPostBack property). you grid control sorting doing in client side. but posting to server side and rendering to client side you sorting removed. You can use Callback.
Ex:
<dx:ASPxGridView ID="grid" runat="server" ClientInstanceName="grid" OnCustomCallback="ASPxGridView1_CustomCallback">
<Columns>
<dx:GridViewDataColumn>
<DataItemTemplate>
<dx:ASPxCheckBox ID="checkbox" runat="server" />
</DataItemTemplate>
</dx:GridViewDataColumn>
</Columns>
</dx:ASPxGridView>
<dx:ASPxButton ID="btnSend" runat="server" AutoPostBack="False" Text="Send" Width="100px" ClientInstanceName="btnSend">
<ClientSideEvents Click="function(s, e) { grid.PerformCallback(); }" />
</dx:ASPxButton>
Code behind:
if (!IsPostBack)
{
//Some stuff
grid.DataSource = sourceTable;
grid.DataBind();
//Other stuff
}
protected void ASPxGridView1_CustomCallback(object sender, DevExpress.Web.ASPxGridViewCustomCallbackEventArgs e)
{
for (int i = 0; i < grid.VisibleRowCount; i++)
{
//Other stuff
ASPxCheckBox checkbox = grid.FindRowCellTemplateControl(i, grid.DataColumns[0], "checkbox") as ASPxCheckBox;
if (checkbox.Checked) //Always false
{
//Do conditional stuff
}
//More stuff
}
}
show difference between callback and postback in c#
Difference between a Postback and a Callback
There are some variants.
Page_Init event handler
You can try to move your binding code to Page_Init event handler.
protected void Page_Init(object sender, EventArgs e)
{
grid.DataSource = sourceTable;
grid.DataBind();
}
PostData of CheckBox editor is loaded between Page_Init and Page_Load, so the values in your CheckBox column are going to be erased in Page_Load event after calling to grid.DataBind method.
GridViewCommandColumn with ShowSelectCheckbox="true"
Here is another possibility. You can imitate the desired behavior by using GridViewCommandColumn with ShowSelectCheckbox property.
<dx:GridViewCommandColumn ShowSelectCheckbox="true" />
You can use grid.Selection.IsRowSelected method to get the checked rows .
Here is example:
protected void Button1_Click(object sender, EventArgs e)
{
//Some stuff
for (int i = 0; i < grid.VisibleRowCount; i++)
{
//Other stuff
if (grid.Selection.IsRowSelected(i))
{
//Do conditional stuff
}
//More stuff
}
//Even more stuff
}

Add radio button list items programmatically in asp.net

I have a radio button list whose items I need to add on Page_Load
aspx code
<asp:radioButtonList ID="radio1" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
</asp:radioButtonList>
code behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
radioList.Items.Add(new ListItem("Apple", "1"));
}
After the control reaches radioList.Items.Add
I keep getting the Object reference not set to instance of an object
error
What am I doing wrong?
You don't need to to do a FindCOntrol. As you used the runat="server" attributes, just get the reference of your RadioList via its name "radio1"
protected void Page_Load(object sender, EventArgs e)
{
radio1.Items.Add(new ListItem("Apple", "1"));
}
By using
RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
radioList.Items.Add(new ListItem("Apple", "1"));
you are not adding your list on the control on your page, but on an un-instanciated Radiobuttonlist called radioList.
If the page is reachable from the class, use
radio1.Items.Add(new ListItem("Apple", "1"));
you must add !ispostback
if (!IsPostBack)
{
radio1.Items.Add(new ListItem("Apple", "1"));
}
As an alternative to using the < asp: **> tools -
I needed to reuse a radio option which relies on a lot of jQuery integration in the site. (Also wanted to avoid just CSS hiding the content within the html code of the aspx page.)
The radio buttons needed only appear in an 'edit' page depending on security ACU level logic within the codebehind and rendered with currently stored item value data found in the db.
So I used the following:
string RadioOnChk1 = (db.fieldChecked == true) ? "checked='checked'" : "";
string RadioOnChk2 = (db.fieldChecked == false) ? "checked='checked'" : "";
if (ACU > 3)
{
// Create radio buttons with pre-checked
StringBuilder RadioButtns = new StringBuilder(); // Form input values
{
RadioButtns.Append("<p><label><input type=\"radio\" id=\"radiocomm1\" name=\"custmComm\" value=\"1\"");
RadioButtns.Append(RateIncChk1 + "/>Included or </label>");
RadioButtns.Append("<label><input type=\"radio\" id=\"radiocomm2\" name=\"custmComm\" value=\"2\"");
RadioButtns.Append(RateIncChk2 + "/>Excluded</label>");
RadioButtns.Append("</p>");
}
htmlVariable = (RadioButtns.ToString());
}
It works.. Is this a wrong way of going about it?

Dropdownlist SelectedIndexChanged firing on every postback

I am dynamically adding a custom user control to an update panel. My user control contains two dropdownlists and a textbox. When a control outside of the update panel triggers a postsback, I am re-adding the user control to the update panel.
The problem is...on postback when I re-add the user controls, it's firing the "SelectedIndexChanged" event of the dropdownlists inside the user control. Even if the selectedindex did not change since the last postback.
Any ideas?
I can post the code if necessary, but there's quite a bit in this particular scenario.
Thanks in advance!
EDIT...CODE ADDED BELOW
*.ASCX
<asp:DropDownList ID="ddlColumns" OnSelectedIndexChanged="ddlColumns_SelectedChanged" AppendDataBoundItems="true" AutoPostBack="true" runat="server">
*.ASCX.CS
List<dataColumnSpecs> dataColumns = new List<dataColumnSpecs>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillDDLColumns();
}
}
public void fillDataColumnsList()
{
dataColumns.Clear();
//COMMON GETDATATABLE RETURNS A DATA TABLE POPULATED WITH THE RESULTS FROM THE STORED PROC COMMAND
DataTable dt = common.getDataTable(storedProcs.SELECT_COLUMNS, new List<SqlParameter>());
foreach (DataRow dr in dt.Rows)
{
dataColumns.Add(new dataColumnSpecs(dr["columnName"].ToString(), dr["friendlyName"].ToString(), dr["dataType"].ToString(), (int)dr["dataSize"]));
}
}
public void fillDDLColumns()
{
fillDataColumnsList();
ddlColumns.Items.Clear();
foreach (dataColumnSpecs dcs in dataColumns)
{
ListItem li = new ListItem();
li.Text = dcs.friendlyName;
li.Value = dcs.columnName;
ddlColumns.Items.Add(li);
}
ddlColumns.Items.Insert(0, new ListItem(" -SELECT A COLUMN- ", ""));
ddlColumns.DataBind();
}
protected void ddlColumns_SelectedChanged(object sender, EventArgs e)
{
//THIS CODE IS BEING FIRED WHEN A BUTTON ON THE PARENT *.ASPX IS CLICKED
}
*.ASPX
<asp:UpdatePanel ID="upControls" runat="server">
<ContentTemplate>
<asp:Button ID="btnAddControl" runat="server" Text="+" OnClick="btnAddControl_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" ValidationGroup="vgGo" />
<asp:GridView...
*.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
uc_Counter = 0;
addControl();
gridview_DataBind();
}
else
{
reloadControls();
}
}
protected void btnGo_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//THIS BUTTON CLICK IS WHAT'S TRIGGERING THE
//SELECTEDINDEXCHANGED EVENT TO FIRE ON MY *.ASCX
gridview_DataBind();
}
}
private void reloadControls()
{
int count = this.uc_Counter;
for (int i = 0; i < count; i++)
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + i;
upControls.ContentTemplateContainer.Controls.AddAt(i, myUserControl);
((customUserControl)myUserControl).fillDDLColumns();
}
}
private void addControl()
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + uc_Counter.ToString();
upControls.ContentTemplateContainer.Controls.AddAt(upControls.ContentTemplateContainer.Controls.IndexOf(btnAddControl), myUserControl);
//((customUserControl)myUserControl).fillDDLColumns();
this.uc_Counter++;
}
protected int uc_Counter
{
get { return (int)ViewState["uc_Counter"]; }
set { ViewState["uc_Counter"] = value; }
}
Even though this is already answered I want to put an answer here since I've recently tangled with this problem and I couldn't find an answer anywhere that helped me but I did find a solution after a lot of digging into the code.
For me, the reason why this was happening was due to someone overwriting PageStatePersister to change how the viewstate hidden field is rendered. Why do that? I found my answer here.
One of the greatest problems when trying to optimize an ASP.NET page to be more search engine friendly is the view state hidden field. Most search engines give more score to the content of the firsts[sic] thousands of bytes of the document so if your first 2 KB are view state junk your pages are penalized. So the goal here is to move the view state data as down as possible.
What the code I encountered did was blank out the __VIEWSTATE hidden fields and create a view_state hidden field towards the bottom of the page. The problem with this is that it totally mucked up the viewstate and I was getting dropdownlists reported as being changed when they weren't, as well as having all dropdownlists going through the same handler on submit. It was a mess. My solution was to turn off this custom persister on this page only so I wouldn't have to compensate for all this weirdness.
protected override PageStatePersister PageStatePersister
{
get
{
if (LoginRedirectUrl == "/the_page_in_question.aspx")
{
return new HiddenFieldPageStatePersister(Page);
}
return new CustomPageStatePersister(this);
}
}
This allowed me to have my proper viewstate for the page I needed it on but kept the SEO code for the rest of the site. Hope this helps someone.
I found my answer in this post .net DropDownList gets cleared after postback
I changed my counter that I was storing in the viewstate to a session variable.
Then I moved my reloadControls() function from the Page_Load of the *.ASPX to the Page_Init.
The key was dynamically adding my user control in the Page_Init so it would be a member of the page before the Viewstate was applied to controls on the page.

Setting SelectedValue of a data bound DropDownList

I have an asp.net dropDownList which is automatically bound to a sqlDataSource to values of client type on page load. On page load I am also creating a Client object, one of it's properties is ClientType. I am trying to set the SelectedValue of the ddl according to the value of the ClientType property of the Client object unsuccessfully. I recieve the following error message "System.ArgumentOutOfRangeException: 'ddlClientType' has a SelectedValue which is invalid because it does not exist in the list of items". I understand that this is because the list has not yet been populated when I'm trying to set the selected value. Is there a way of overcoming this problem? Thank you!
You have to use the DataBound Event, it will be fired, once databinding is complete
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
// You need to set the Selected value here...
}
If you really want to see the value in the Page load event, then call the DataBind() method before setting the value...
protected void Page_Load(object sender, EventArgs e)
{
DropdownList1.DataBind();
DropdownList1.SelectedValue = "Value";
}
Before setting a selected value check whether item is in list and than select it by index
<asp:DropDownList id="dropDownList"
AutoPostBack="True"
OnDataBound="OnListDataBound"
runat="server />
protected void OnListDataBound(object sender, EventArgs e)
{
int itemIndex = dropDownList.Items.IndexOf(itemToSelect);
if (itemIndex >= 0)
{
dropDownList.SelectedItemIndex = itemIndex;
}
}
EDIT: Added...
If you are doing binding stuff in Page Load, try to follow this way:
Move all binding related code in overriden DataBind() method
In Page_Load of Page add: (in case of control do not call DataBind directrly, this is a responsibility of a parent page)
if (!IsPostBack)
{
Page.DataBind(); // only for pages
}

Categories

Resources