save state in postback for a data-bound control - asp.net

I have a repeater with one delete button and bind it to a list like this:
page_load()
{
list<person> myList = new list<person>()
myList.add(new person(Id="1",Name="n1"));
if(!isPostBack)
{
myList.add(new person(Id="2",Name="n2"));
myRepeater.DataSource = myList;
myrepeater.DataBind();
}
myRepeater.ItemCommand += myHandler;
}
void AdverticRp_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName == "delete")
{
FileUploader fu = myrepeater.FindControl("fu") as FileUploadr;
// do somthing ** * but contorls is null refrence ***
}
}
the repeater bind successfully and delete button raised correctly but i want get contorls in myrepeater but they are null refrence. i know why. because repeater not binded in postback. what should i do? must save state of repeater in veiwsate?
I think im wrong in binding. but what is the correct one?
I appreciate for all help.

If you disable viewstate, you won't see them unless you databind on every page load. You are getting your values from viewstate
Check link.

Find the control from the repeater's Items, not on the repeater itseld. Try this:
void AdverticRp_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName == "delete")
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
FileUploader fu = item.FindControl("fu") as FileUploader;
// do somthing here
}
}
}

Related

How to detect repeater on OnCheckedChanged event of radio button

I have a nested repeater and there is a radiobutton in the inner one ( rptrSubscriptions ). What I want to do is to highlight the radio button that is selected and unhighlight the previous one .
There must be only one radio button selected between all of the radio buttons in the outer repeater .I also need to save the itemID of the selected one in a hidden field.
I have developed a method with the name of HighlightSubscription that will be called when user clicks on the radio button (OnCheckedChanged="HighlightSubscription") .
The problem is this, the system doesn't recognize rptrSubscriptions in HighlightSubscription method, I tried to use findcontrol but unfortunately there is no access to e.items in this method.
I also defined rptrSubscriptions as a public variable but it will be null too in this method.
I have copied the source of HighlightSubscription from HighlightBox that is a radio button inside a single repeater and it works fine as its definition is inside the designer,
but for the nested repeater the definition cant be in the designer as the system automatically removes it in compile time.
Any suggestion is highly appreciated.
protected void rptrSubscriptionGroups_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Repeater rptrSubscriptions = (Repeater)e.Item.FindControl("rptrSubscriptions");
if (rptrSubscriptions != null)
{
RepeaterItem item = e.Item;
if (e.Item.ItemType == (ListItemType.Item) || e.Item.ItemType == (ListItemType.AlternatingItem))
{
DataTable SubscriptionTbl = SubscriptionsBind(SelectedLanguageID, SelectedPlatformID, SelectedCurrencyID, SelectedGroupID, 1);
rptrSubscriptions.DataSource = SubscriptionTbl;
rptrSubscriptions.DataBind();
}
}
}
protected void HighlightSubscription(object source, EventArgs e)
{
//find previous selected row
if (hiddenSelectedSubscriptionRowIndex.Value.Length > 0)
{
int rowIndex = int.Parse(hiddenSelectedSubscriptionRowIndex.Value);
//Repeater rptrSubscriptions = (Repeater)e.Item.FindControl("rptrSubscriptions");
RepeaterItem item = rptrSubscriptions.Items[rowIndex];
if (rptrSubscriptions != null)
{
// Uncheck Old Radio Button
RadioButton rbOld = (RadioButton)item.FindControl("rbBox");
rbOld.Attributes.CssStyle.Add("border-color", "lightgray");
rbOld.Attributes.CssStyle.Add("border-width", "1px");
rbOld.Checked = false;
}
}
RadioButton rb = source as RadioButton;
int CurrentrepeaterItemIndex = ((RepeaterItem)rb.NamingContainer).ItemIndex;
// save current row index in a hiddden field
hiddenSelectedSubscriptionRowIndex.Value = CurrentrepeaterItemIndex.ToString();
}
<asp:Repeater ID="rptrSubscriptionGroups" runat="server" OnItemDataBound="rptrSubscriptionGroups_ItemDataBound" OnItemCommand="rptrSubscriptionGroups_ItemCommand">
<ItemTemplate>
<asp:Repeater ID="rptrSubscriptions" runat="server" OnItemDataBound="rptrSubscriptions_ItemDataBound" OnItemCommand="rptrSubscriptions_ItemCommand">
<ItemTemplate>
<asp:RadioButton ID="rbSubscription" runat="server" OnCheckedChanged="HighlightSubscription" AutoPostBack="true"/>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
A little edit from me you can try this one :
protected void HighlightSubscription(object source, EventArgs e)
{
Repeater rptrSubscriptions = new Repeater();
foreach (RepeaterItem a in rptrSubscriptionGroups.Items)
{
rptrSubscriptions = (Repeater)a.FindControl("rptrSubscriptions");
}
//find previous selected row
if (hiddenSelectedSubscriptionRowIndex.Value.Length > 0)
{
int rowIndex = int.Parse(hiddenSelectedSubscriptionRowIndex.Value);
//Repeater rptrSubscriptions = (Repeater)e.Item.FindControl("rptrSubscriptions");
RepeaterItem item = rptrSubscriptions.Items[rowIndex];
if (rptrSubscriptions != null)
{
// Uncheck Old Radio Button
RadioButton rbOld = (RadioButton)item.FindControl("rbBox");
rbOld.Attributes.CssStyle.Add("border-color", "lightgray");
rbOld.Attributes.CssStyle.Add("border-width", "1px");
rbOld.Checked = false;
}
}
RadioButton rb = source as RadioButton;
int CurrentrepeaterItemIndex = ((RepeaterItem)rb.NamingContainer).ItemIndex;
// save current row index in a hiddden field
hiddenSelectedSubscriptionRowIndex.Value = CurrentrepeaterItemIndex.ToString();
}
Something like this:
protected void rptrSubscriptionGroups_ItemDataCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RepeaterItem item = e.Item;
RadioButton rb = (RadioButton)item.FindControl("rbSubscription");
rb.AutoPostBack = true;
rb.CheckedChanged += new EventHandler(rb_CheckChanged);
}
}
private void rb_CheckChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if(rb.Checked == true){
HighlightSubscription();
}
}

how to data bind to dropdownlist when checkbox is checked in asp.net

I have a project that using dropdownlist for choices.When check checkbox1 dropdown automatically bind data from database using table1 and when I check checkbox2 dropdown automatically binding data from database using table2.I do not want to use get data by using any button .How can I do that .Please help me.
here is code by using button:
public void LokasyonDoldur()
{
birimBUS = new BirimBUSV1();
List<BirimVO> birimVO = new List<BirimVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
birimVO = birimBUS.LokasyonlariGetir();
foreach (var item in birimVO)
{
items.Add(new ListItem(item.BirimAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
public void BirimleriDoldur()
{
PoliklinikBUS poliklinikBUS = new PoliklinikBUS();
List<PoliklinikVO> poliklinikVO = new List<PoliklinikVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
poliklinikVO = poliklinikBUS.Poliklinikler();
foreach (var item in poliklinikVO)
{
items.Add(new ListItem(item.PoliklinikAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
protected void BtnLokasyon_Click(object sender, EventArgs e)
{
if (ChckLctn.Checked == true && ChckBrm.Checked==false)
{
LokasyonDoldur();
}
else if (ChckLctn.Checked == false && ChckBrm.Checked == true)
{
BirimleriDoldur();
}
else
{
}
Button1.Visible = true;
BtnLokasyon.Visible = false;
}
protected void DrpChcs_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
KirilimId = Int32.Parse(DrpChcs.SelectedValue);
BPolikilinikID= KirilimId;
}
but I do not want to use this one.
ohh its another language. its hard to read. but what you basicly have to do is check which checkbox is checked in the page load and then load the dropdown based on what is loaded.
something like this. (I have typed it from my head so its not like copy-paste but you get the idea)
page_load
{
if(checkbox1.checked)
{
dropdown.dataitems = items1;
dropdown.databind();
return;
}
if(checkbox2.checked)
{
dropdown.dataitems = items2;
dropdown.databind();
return;
}
}
YOu can call the Button1_click event from the Dropdown list selected index changed event like this
Button1_Click(Button1,new EventArgs());
and in this you can hide that button from the page and in code behind you are calling the same function
OR
You can refactor the code in a seperate function from the button click event and call that function in the selected index changed event.
Please let me knwo if I misunderstood your question
Thanks

how to define radio button CheckedChanged property after finding radio button in another control

i like to know how i have to use radio button CheckedChanged property when the radio button there is in gridview and this gridview itself is inside of 1 user control and user control is inside of detail view control.
before i have learned how i have to find radio button control in another control. but after finding i do not know how to make CheckedChanged property for that?
protected void btnShowAddTransmittaltoCon_Click(object sender, EventArgs e)
{
Transmittallistfortest transmittalList = (Transmittallistfortest)DetailsView1.FindControl("Transmittallistfortest1");
GridView g3 = transmittalList.FindControl("GridViewTtransmittals") as GridView;
foreach (GridViewRow di in g3.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
//Giving Error:Object reference not set to an instance of an object.
if (rad != null && rad.Checked)
{
var w = di.RowIndex;
Label1.Text = di.Cells[1].Text;
}
Replace this
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
with this:
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
You won't get an exception but it may return NULL - in which case it'll be caught in the ifstatement: rad != null.
The whole point of using the as keyword is this:
as => won't throw an exception - it just reports null.
By the way: You should retrieve the RadioButton this way:
if(di.RowType == DataControlRowType.DataRow)
{
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
}
To define the CheckedChange event, do this:
//rad.Checked = true;
rad.CheckedChanged += new EventHandler(MyCheckedChangeEventHandler);
Then define the handler:
protected void MyCheckedChangeEventHandler)(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if (rb.Checked)
{
// Your logic here...
}
}

Unable to FindControl() in ListView ItemEditing

I have a ListView in an ASP.NET web application. When a user clicks the edit button, I want textfields to pop up that are dependent on certain values of the item. However, I can't seem to find any controls inside of my ListView1_ItemEditing() function.
I have read the Microsoft documentation and various help threads on the internet, but their suggestions do not appear to work for me. This is generally what I see:
ListViewItem item = ProductsListView.Items[e.NewEditIndex];
Label dateLabel = (Label)item.FindControl("DiscontinuedDateLabel");
For the sake of simplicity I just want to be able to select a label in ListView1_ItemEditing(). This is the code in ListView1_ItemEditing():
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
DataBind(); //not sure if this does anything
ListViewItem item = ListView1.Items[e.NewEditIndex];
Label debugLabel = (Label)item.FindControl("label_editing");
debugLabel.Text = "Works";
}
Here is the ASP
<EditItemTemplate>
<asp:Label ID="label_editing" runat="server" Text="hello world"></asp:Label>
</EditItemTemplate>
When debugging, item and debugLabel are both NULL.
UPDATE: I resolved this issue by moving my logic to ItemDataBound and then checking if my tr (containing textboxes) was in that particular data item. Code below:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Control tr_verizon = e.Item.FindControl("tr_verizonEdit");
Control tr_att = e.Item.FindControl("tr_attEdit");
if (tr_verizon != null)
{
//Control tb_meid = e.Item.FindControl("TextBox_Meid");
Label lbl_carrierId = (Label)e.Item.FindControl("lbl_carrierId");
if (lbl_carrierId == null)
{
Message.Text = "lbl_carrierId is null!";
}
else if (lbl_carrierId.Text.Equals(""))
{
Message.Text = "lbl_carrierId is empty!";
}
else
{
string recordId = lbl_carrierId.Text;
if (tr_verizon != null && tr_att != null)
{
if (lbl_carrierId.Text.Equals("1"))
{
tr_verizon.Visible = false;
tr_att.Visible = true;
}
else
{
tr_verizon.Visible = true;
tr_att.Visible = false;
}
}
}
}
}
}
The ItemEditing event is raised when an item's Edit button is clicked, but before the ListView item is put in edit mode. Therefore controls in EditItemTemplate are not available at this time.
More Info and example
You should do the DataBind() first, like this:
ListView1.EditIndex = e.NewEditIndex;
ListView1_BindData(); // a function that get the DataSource and then ListView1.DataBind()
// Now find the control as you did before
Have you tried casting the sender object instead of trying to access your ListViewItem by index?
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
var item = sender as ListViewItem;
var debugLabel = item.FindControl("label_editing") as Label;
debugLabel.Text = "Works";
}

Control caused the post back

I have a form that contains a dropdownlist,
on index changed method,i will call my user control class .cs with parameters choosen by the user, when im putting my code inside the index changed like the code below, it doesnt work, which is a normal behavior:
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e)
{
....
MyUsercontrol c = new MyUSercontrol(....);
this.panel.controls.add(c);
}
thats why i have to put the code inside my onload method, but the thing is how can i know if it is the ddl that caused the post back? is there a propertie? or should i use page.Request.Params.Get("__EVENTTARGET") technic ?
Thanks alot !
If your MyUserControl is really user control, that means .ascx file, you should use this:
Page.LoadControl("~/Controls/MyUserControl.ascx")
instead of creating the instance of the control by calling constructor directly.
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e) {
....
var c = Page.LoadControl("~/Controls/MyUserControl.ascx");
this.panel.controls.add(c);
}
EDIT:
But of course, after every other post back, you will lose this control. So you should also make sure that you will create all dynamic controls during OnLoad event.
set the property autoPostBack=true on the dropdownlist in order for the page to postback
Or use the below function to get the post back control on the page_load
private string GetPostBackControl()
{
string retVal = string.Empty;
try
{
string ctrlname = Page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
Control ctrl = this.Page.FindControl(ctrlname);
if (ctrl != null)
{
retVal = ctrl.ID;
}
}
}
catch (Exception ex) { ManageException(ex, ShowGeneralErrorMessage); }
return retVal;
}
Try setting AutoPostBack="True" property of drop down list. After setting this property when you select an item in list it will automatically do the postback and your event ResourceTypesDDL_SelectedIndexChanged will be fired.

Resources