ASP.NET button does not run the related function - asp.net

I have an UpdatePanel, in it a GridView, and in it a Repeater. There is a button to add comment. This button post backs but id does not run the function code behind. Here is my code
<updatepanel>
<gridview>
<repeater>
<asp:Button ID="kitapVarYorumEkle" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName='<%# GridView1.Rows.Count.ToString() %>'
Text="Yorum ekle" class="blueButton"
OnClick="kitapVarYorumEkle_Click" />
</repeater>
</gridview>
</updatepanel>
Code inside the js is:
protected void kitapVarYorumEkle_Click(object sender, EventArgs e)
{
kitapVarYorum temp = new kitapVarYorum();
if (Session["id"] != null)
{
temp.uyeId = Convert.ToInt32(Session["id"]);
}
Button btn = (Button)sender;
temp.kitapVarId = Convert.ToInt32(btn.CommandArgument);
string text = "";
GridViewRow row = GridView1.Rows[Convert.ToInt32(btn.CommandName)];
if (row != null)
{
TextBox txt = row.FindControl("txtYorum") as TextBox;
if (txt != null)
{
text = txt.Text;
}
}
temp.icerik = text;
var db = Tools.DBBaglanti();
db.kitapVarYorums.InsertOnSubmit(temp);
db.SubmitChanges();
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
I have tried it outside the the controls and it works

Have you tried the ItemCommand approach?
<asp:Button
CommandArgument='<%#Eval("id") %>'
CommandName="yourCommandNameOfChoice"
Text="Yorum ekle"
ID="kitapVarYorumEkle"
class="blueButton" runat="server"
OnClick="kitapVarYorumEkle_Click" />
now add an ItemCommand event for your repeater:
protected void yourRepeater_ItemCommand(object source , RepeaterCommandEventArgs e)
{
switch(e.CommandName)
{
case "yourCommandNameOfChoice":
// Your Code Here
break;
}
}

Related

RadGrid: Get the modified Items on edit

On a RadGrid I can use the CommandItemTemplate to define my own buttons for, in my case, Save and Cancel the edit (like below)
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
On the code behind, I set up the ItemCommand.
> protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName.CompareTo("UpdateEdited") == 0)
{
var commandItem = ((GridCommandItem)e.Item);
//Updade code here.
}
}
How can I access the modified row with the modified fields so I can perform an updade?
You should have them in command item and you can access them like this:
GridDataItem item = (GridDataItem)e.Item;
string value = item["ColumnUniqueName"].Text;
Is this what you want ? Just a sample you might need to modify it..
.aspx
<telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="rg_NeedDataSource" OnItemCommand="rg_ItemCommand"
MasterTableView-CommandItemDisplay="Top" OnItemDataBound="rg_ItemDataBound">
<MasterTableView EditMode="InPlace">
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server"
CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server"
CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("A") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt" runat="server"
Text='<%# Eval("A") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit"
CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate> </EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Rows.Add("A1");
// Check & Bind
if (dt != null)
{
// Viewstate
ViewState["Data"] = dt;
rg.DataSource = dt;
rg.DataBind();
dt.Dispose();
}
}
}
protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
protected void rg_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "UpdateEdited")
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
// Loop All
foreach (GridEditableItem item in rg.Items)
{
// Find Control
TextBox txt = item.FindControl("txt") as TextBox;
// Check & Add to DataTable
if (txt != null) dt.Rows.Add(txt.Text.Trim());
}
// Check
if (dt != null && dt.Rows.Count > 0)
{
// Set Viewstate
ViewState["Data"] = dt;
// Bind
rg.DataSource = dt;
rg.DataBind();
// Dispose
dt.Dispose();
}
}
else if (e.CommandName == "CancelAll")
{
// Clear Edit Mode
rg.MasterTableView.ClearChildEditItems();
// Rebind
rg.Rebind();
}
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridCommandItem)
{
// Find Control
LinkButton btnUpdateEdited = e.Item.FindControl("btnUpdateEdited") as LinkButton;
LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
// Get is Edit Mode ?
if (rg.EditIndexes.Count > 0)
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = true;
if (btnCancel != null) btnCancel.Visible = true;
}
else
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = false;
if (btnCancel != null) btnCancel.Visible = false;
}
}
}

PagedDataSource and UpdatePanel don't work together

I have a problem with PagedDataSource and UpdatePanel.When I use AsyncPostBackTrigger in my buttons, paging in my page disappear.
Here's asp code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="DataListGallery" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" OnItemDataBound="DataListGallery_ItemDataBound" >
<ItemTemplate>
<asp:HiddenField ID="FieldPhoneId" Value='<%# Eval("Phone_InfoID") %>' runat="server" />
<asp:ImageButton ID="btnShop" OnClick="btnShop_Click" ImageUrl="images/cart.gif" CssClass="left_bt_item" title="header=[خريد] body=[ ] fade=[on]" runat="server" />
<asp:ImageButton CssClass="left_bt_item" title="header=[مورد علاقه] body=[ ] fade=[on]" OnClick="btnFavourite_Click" ID="btnFavourite" ImageUrl="images/unfav.png" runat="server" />
.
.
.
Here's C# code(load event):
protected void Page_Load(object sender, EventArgs e)
{
//http://www.aspdotnetfaq.com/Faq/how-to-determine-whether-an-asynchronous-partial-postback-has-occurred-on-page.aspx
// get a reference to ScriptManager and check if we have a partial postback
if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
{
// partial (asynchronous) postback occured
// insert Ajax custom logic here
}
// enable property is re-creating page controls
else if (!Page.IsPostBack || enable)
{
//enable = false;
if (Page.Request["Page"] != null || Page.Request["Page"] != "")
{
.
.
.
And a button with AsyncPostBackTrigger:
protected void btnFavourite_Click(object sender, ImageClickEventArgs e)
{
// Access to real ImageButton from repeater
ImageButton ib = (ImageButton)sender;
HiddenField hf = (HiddenField)ib.Parent.FindControl("FieldPhoneId");
Favourite objFav = new Favourite(Convert.ToInt32(hf.Value));
Guid userId = objFav.GetUserIdFromUserName(User.Identity.Name);
using (var context = new MobileGalleryEntities())
{
try
{
// Delete favorited
if (objFav.HadFavorited(User.Identity.Name))
{
int phoneInfoId = Convert.ToInt32(Convert.ToInt32(hf.Value));
// Remove favourite
objFav.RemoveFromFavourite(userId);
// Change image
ib.ImageUrl = "~/images/unfav.png";
}
// Add favorite
else
{
// Add phone
objFav.AddToFavourite(userId);
// Change image
ib.ImageUrl = "~/images/favs.gif";
}
}
catch (Exception ex)
{
}
}
}
Here's DataBound event:
protected void DataListGallery_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (User.Identity.IsAuthenticated)
{
try
{
// Get LoginView for access to ImageButton on it.
var loginView = e.Item.FindControl("LoginView1");
ImageButton btnCom = (ImageButton)e.Item.FindControl("btnCompare");
//ImageButton btnFav = (ImageButton)loginView.FindControl("btnFavourite");
ImageButton btnFav = (ImageButton)e.Item.FindControl("btnFavourite");
btnFav.Visible = true;
ImageButton btnShop = (ImageButton)e.Item.FindControl("btnShop");
btnShop.Visible = true;
//HiddenField hf = (HiddenField)loginView.FindControl("FieldPhoneId");
HiddenField hf = (HiddenField)e.Item.FindControl("FieldPhoneId");
List<int> listFav = (List<int>)Session["Fav"];
if (listFav.Contains(int.Parse(hf.Value)))
btnFav.ImageUrl = "~/images/favs.gif";
}
catch(Exception ex)
{
}
}
else
{
ImageButton btnFav = (ImageButton)e.Item.FindControl("btnFavourite");
btnFav.Visible = false;
ImageButton btnShop = (ImageButton)e.Item.FindControl("btnShop");
btnShop.Visible = false;
}
}
When I fire btnFavourite button, paging in my page disapear. but when i use FullPostBack it's work.
Notice that when I use FullPostBack, I re-create controls such as paging control and other control but when I use AsyncPostBackTrigger I didn't re-create controls.
What am I doing?
Thanks.
I have to re-create controls again the same as FullPostBack.

Getting values from textbox in the repeater in button click event

I have a TextBox in a repeater that is populated from the database in the ItemDataBound event. When I tried to get the text inside the TextBox in a Button_Click event I found the TextBox.Text empty. How can I get the Text?
foreach (RepeaterItem repeated in repEdit.Items)
{
DropDownList drp = (DropDownList)FindControlRecursive(repeated, "drpdown");
TextBox txt = (TextBox)FindControlRecursive(repeated, "txt");
CheckBox chk = (CheckBox)FindControlRecursive(repeated, "chk");
if (drp != null && !string.IsNullOrEmpty(drp.Attributes["ID"]))
{
loc.GetType().GetProperty(drp.Attributes["ID"].Split('#')[0] + "ID").SetValue(loc, int.Parse(drp.SelectedValue), null);
}
if (txt != null && !string.IsNullOrEmpty(txt.Attributes["ID"]))
{
if (txt.Attributes["ID"].Contains("#int"))
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, int.Parse(txt.Text), null);
}
else if (txt.Attributes["ID"].Contains("#decimal"))
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, decimal.Parse(txt.Text), null);
}
else
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, txt.Text, null);
}
}
if (chk!=null && !string.IsNullOrEmpty(chk.Attributes["ID"]))
{
loc.GetType().GetProperty(chk.Attributes["ID"].Split('#')[0]).SetValue(loc, chk.Checked, null);
}
}
HTML
<asp:Repeater ID="repEdit" runat="server" OnItemDataBound="repEdit_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Visible="false"></asp:Label>
<asp:TextBox ID="txt" runat="server" Visible="false"></asp:TextBox>
<asp:CheckBox ID="chk" runat="server" Visible="false" />
<asp:DropDownList ID="drpdown" runat="server" Visible="false">
</asp:DropDownList>
<br />
</ItemTemplate>
</asp:Repeater>
Here is the itemdatabound event
protected void repEdit_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Label name = e.Item.FindControl("lblName") as Label;
TextBox text = e.Item.FindControl("txt") as TextBox;
CheckBox chk = e.Item.FindControl("chk") as CheckBox;
DropDownList drp = e.Item.FindControl("drpdown") as DropDownList;
Button but = e.Item.FindControl("butEdit") as Button;
//butEdit.Visible = true;
if (but != null)
{
but.Visible = true;
}
if (e.Item.ItemType == ListItemType.Item)
{
KeyValuePair<string, Dictionary<int, string>> kvp = (KeyValuePair<string, Dictionary<int, string>>)e.Item.DataItem;
if (name != null)
{
if (kvp.Key.Contains("#datetime"))
{
return;
}
name.Visible = true;
name.Text = kvp.Key.Split('#')[0].ToString();
}
if (kvp.Key.Contains("#int") || kvp.Key.Contains("#decimal"))
{
text.Visible = true;
text.ID = kvp.Key;
text.EnableViewState = true;
text.Attributes["ID"] = kvp.Key;
text.Text = kvp.Value[0].ToString();
if (kvp.Key.Split('#')[0] == "ID")
{
text.Enabled = false;
}
}
Here is your Repeater. It has a PlaceHolder and Button.
<asp:Repeater ID="rpNotifications" runat="server"
OnItemDataBound="rpNotifications_ItemDataBound">
<ItemTemplate>
<asp:PlaceHolder ID="commentHolder" runat="server"></asp:PlaceHolder>
<asp:Button runat="server" ID="btnComment"
Text="Comment" CssClass="btn blue"
OnClick="btnComment_Click" CommandArgument='<%# Eval("id") %>' />
</ItemTemplate>
</asp:Repeater>
The button has the command argument set as the Id of the data I am binding to it.
Next here is where you need to Bind your Repeater. If you don't Bind it in the Page_Init the resulting values in the dynamically created controls will be lost.
protected void Page_Init(object sender, EventArgs e)
{
rpNotifications.DataSource = {datasource-here}
rpNotifications.DataBind();
}
And here is why (Image from: http://msdn.microsoft.com/en-us/library/ms972976.aspx)
Dynamically Create Control on ItemDataBound
You will need to add the textbox to the placeholder as this is the only way to dynamically assign an ID to the control.
protected void rpNotifications_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
Common.Models.Item item = (Common.Models.Item)e.Item.DataItem;
// Create new Control
TextBox txtComment = new TextBox();
txtComment.ID = String.Format("txtComment{0}", item.id.ToString());
// Ensure static so you can reference it by Id
txtComment.ClientIDMode = System.Web.UI.ClientIDMode.Static;
// Add control to placeholder
e.Item.FindControl("commentHolder").Controls.Add(txtComment);
}
}
Get Value On Button Click
Now you need to create the event handler for the button and get the resulting value
protected void btnComment_Click(object sender, EventArgs e)
{
// This is the ID I put in the CommandArgument
Guid id = new Guid(((Button)sender).CommandArgument);
String comment = String.Empty;
// Loop through the repeaterItems to find your control
foreach (RepeaterItem item in rpNotifications.Controls)
{
Control ctl = item.FindControl(
String.Format("txtComment{0}", id.ToString()));
if (ctl != null)
{
comment = ((TextBox)ctl).Text;
break;
}
}
}
Try to get ASP.Net controls using below code
DropDownList drp = (DropDownList)repeated.FindControl("drpdown");
TextBox txt = (TextBox)repeated.FindControl("txt");
CheckBox chk = (CheckBox)repeated.FindControl("chk");
Then you can get values from there respective properties.

Failed to load viewstate - dynamic controls in ASP.NET

I have read many articles on viewstate but I can't get my head around it.
Basically I want to have two listboxes with add and remove buttons and a Proceed button.
When the Proceed button is pressed, the previous is hidden and a textbox is presented for each item in the first list box with 2 drop down boxes to describe it + a textbox for each item in the second list box (also for the user to add a description).
I then want a Finalise Button to save all this information to a database.
So far I have the following code:
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
CreateDynamicControls();
Page.MaintainScrollPositionOnPostBack = true;
Build2.Visible = false;
Build3.Visible = false;
Build4.Visible = false;
Finish.Visible = false;
}
void AddC_Click(Object sender, EventArgs e)
{
criteria.Items.Add(addnewc.Text.ToString());
addnewc.Text = null;
}
void RemoveCriterion_Click(Object sender, EventArgs e)
{
for (int i = 0; i < criteria.Items.Count; i++)
{
if (criteria.Items[i].Selected)
{
criteria.Items.Remove(criteria.Items[i]);
i--;
}
}
}
void AddAlternative_Click(Object sender, EventArgs e)
{
alternatives.Items.Add(addnewa.Text.ToString());
addnewa.Text = null;
}
void RemoveAlternative_Click(Object sender, EventArgs e)
{
for (int i = 0; i < alternatives.Items.Count; i++)
{
if (alternatives.Items[i].Selected)
{
alternatives.Items.Remove(alternatives.Items[i]);
i--;
}
}
}
void Continue_Click(Object sender, EventArgs e)
{
Build1.Visible = false;
Build2.Visible = true;
Build3.Visible = true;
CreateDynamicControls();
Finish.Visible = true;
}
void CreateDynamicControls()
{
Build2.Controls.Clear();
Build3.Controls.Clear();
Build2.Controls.Add(new LiteralControl("<h3>Please define each criterion.</h3><p>By describing it and indicating if it is 1/2 and a/b.</p>"));
for (int i = 0; i < criteria.Items.Count; i++)
{
Build2.Controls.Add(new LiteralControl("<strong>" + criteria.Items[i].Text + "</strong> Description:<br />"));
TextBox criteriondesc = new TextBox();
Build2.Controls.Add(criteriondesc);
criteriondesc.ID = "c" + i.ToString();
criteriondesc.Rows = 3;
criteriondesc.Width = 850;
criteriondesc.TextMode = TextBoxMode.MultiLine;
Build2.Controls.Add(new LiteralControl("<br />"));
Build2.Controls.Add(new LiteralControl("Desc1: "));
DropDownList aim = new DropDownList();
aim.ID = i.ToString();
aim.Width = 250;
aim.Items.Add(new ListItem("1"));
aim.Items.Add(new ListItem("2"));
Build2.Controls.Add(aim);
Build2.Controls.Add(new LiteralControl(" Desc2: "));
DropDownList source = new DropDownList();
source.ID = i.ToString();
source.Width = 250;
source.Items.Add(new ListItem("a"));
source.Items.Add(new ListItem("b"));
Build2.Controls.Add(source);
Build2.Controls.Add(new LiteralControl("<br /><br />"));
}
Build3.Controls.Add(new LiteralControl("<h3>Please define each alternative.</h3><p>Please describe each alternaitve in detail.</p>"));
for (int i = 0; i < alternatives.Items.Count; i++)
{
Build3.Controls.Add(new LiteralControl("<strong>" + alternatives.Items[i].Text + "</strong> Description:<br />"));
TextBox altdesc = new TextBox();
altdesc.ID = "a" + i.ToString();
altdesc.Rows = 3;
altdesc.Width = 850;
altdesc.TextMode = TextBoxMode.MultiLine;
Build3.Controls.Add(altdesc);
Build3.Controls.Add(new LiteralControl("<br />"));
}
Build3.Controls.Add(new LiteralControl("<br /><h3>Review dates.</h3><p>Please select a date for a meeting.</p>"));
OboutInc.Calendar2.Calendar selectdates = new OboutInc.Calendar2.Calendar();
Build3.Controls.Add(selectdates);
}
void Finish_Click(Object sender, EventArgs e)
{
Build4.Visible = true;
foreach (var control in Build2.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
foreach (var control in Build3.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
}
</script>
<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
<asp:Panel ID="Build1" runat="server">
<h3>What is your aim?</h3>
<p>
<asp:TextBox ID="goal" runat="server" Width="850px"></asp:TextBox>
</p>
<h3>What are the criteria of your decision?</h3>
<p>
<asp:ListBox ID="criteria" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveCriterion" runat="server" Text="Remove" OnClick="RemoveCriterion_Click" />
<asp:TextBox ID="addnewc" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddC" runat="server" Text="Add" OnClick="AddC_Click" />
</p>
</p>
<h3>What are the alternatives of your decision?</h3>
<p>
<asp:ListBox ID="alternatives" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveAlternative" runat="server" Text="Remove" OnClick="RemoveAlternative_Click" />
<asp:TextBox ID="addnewa" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddAlternative" runat="server" Text="Add" OnClick="AddAlternative_Click" />
</p>
<p align="right"><asp:Button ID="continue" runat="server" Text="Continue" OnClick="Continue_Click" /></p>
</asp:Panel>
<asp:Panel ID="Build2" runat="server">
</asp:Panel>
<asp:Panel ID="Build3" runat="server">
</asp:Panel>
<asp:Panel ID="Build4" runat="server">
</asp:Panel>
<p align="right"><asp:Button ID="Finish" runat="server" Text="Finish" OnClick="Finish_Click" /></p>
</asp:Content>
As you can see, at the minute I am just trying to output the user's text from the dynamically created textbox fields.
However, I am getting the error
Failed to load viewstate. The control tree into which viewstate is
being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial
request.
at: Line 169: Build3.Controls.Add(altdesc);
Does anyone know how to fix this problem with the viewstate?
I am very new to ASP.NET, my background is mainly in WinForms.
Thank you for any help and advice!!
You are creating your controls too late. You should create them during the Init events of the page, and not Page Load. I suggest You read abit about page life cycle
I think the best way to do it, it would be :
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
CreateDynamicControls();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
CreateDynamicControls();<br/>
}
Small sample:
http://class10e.com/Microsoft/which-method-should-you-add-to-the-web-page
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

RadioButtonList Postback Issues

Environment: ASP NET 2.0 - Production Server does not have Ajax Control Toolkit so no real Control toolkit to use here.
3 RadioButtons List:
List one loads, after postback, the item from list one is used to select a Lab value.
Once a lab value is selected a 3rd radiobuttonlist will populate. There are some textboxes but they are not shown in example. The textboxes postback themselves on changes. If both textboxes are
not empty, a record is created for the session.
Now if the 3rd radiobuttonlist is changed from the default a series of 3 hidden user controls appear which represent 3 levels of reasons for the change ( child/parent records in database ).
The problem I am having is when I select a different item on the radiobuttonlist the radiobutton 3 OnSelectedIndex is firing after my user controls fire. My user controls need the value of the 3rd list to go to the database and get the correct set of records associated with the lab.
The problem is because the last radiobuttonlist is not processed until after the web controls loads, the code to mount the user controls never happens.
Here is the basic HTML code:
<asp:RadioButtonList ID="rdoLab" runat="server" OnSelectedIndexChanged="rdoLab_OnSelectedIndexChange">
</asp:RadioButtonList>
<asp:TextBox ID="textbox1" runat="server" OnTextChanged="TextBoxProcess" />
<asp:TextBox ID="textbox2" runat="server" OnTextChanged="TextBoxProcess" />
<asp:RadioButtonList ID="rdoPrimary" RepeatColumns="3" OnSelectedIndexChanged="rdoPrimary_OnSelectedIndexChanged" runat="server" ToolTip="Select Normal, Hypo or Hyper - Normal is default value." AutoPostBack="True" >
<asp:ListItem Value="3" Text="Normal" Selected="true"/>
<asp:ListItem Value="1" Text="Hypo" />
<asp:ListItem Value="2" Text="Hyper" />
</asp:RadioButtonList>
<asp:Panel ID="UpdLab" runat="server" Visible="true" EnableViewState="true">
<asp:Table ID="tblAdmin" runat="server">
<asp:TableRow>
<asp:TableCell runat="server" id="tblCell1" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab1" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell2" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab2" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell3" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab3" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
Here is the page behind:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
GetSessionVars();
if (CommonUI.strTest((string)Session["rdoLabs"]) && CommonUI.strTest((string)Session["rdoPrimary"]) && Convert.ToString(hrdoLabs.Value) == (string)Session["rdoLabs"])
{
divLabLvl.Visible = true;
// Get cboListItems from the web user controls...
Session["ArrLstItems"] = "";
ArrayList ArrLstItems = new ArrayList();
ArrayList GetWuc = GetWUCS();
for (int i = 0; i < GetWuc.Count; i++)
{
Lab wuc = (Lab)GetWuc[i];
CheckBoxList cboItemList = (CheckBoxList)wuc.FindControl("cboItems");
string cboItems = GetCboItemList(cboItemList);
HiddenField hcboItems = (HiddenField)wuc.FindControl("hcboItems");
}
Session["ArrLstItems"] = (ArrayList)ArrLstItems;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbDataReader ddrGrp = rdoGroups();
if (ddrGrp.HasRows)
{
rdoGroup.DataSource = ddrGrp;
rdoGroup.DataBind();
}
ddrGrp.Close();
}
else
{
DbDataReader ddrLab = rdoUserLabs();
if (ddrLab.HasRows)
{
rdoLabs.DataSource = ddrLab;
rdoLabs.DataBind();
if (CommonUI.strTest((string)Session["rdoLabs"]))
{
if (Convert.ToInt32(Session["rdoLabs"]) > 0)
{
rdoLabs.SelectedValue = (string)Session["rdoLabs"];
SetLabCss();
}
}
}
ddrLab.Close();
}
}
protected void rdoGroup_OnSelectedIndexChanged(object sender, EventArgs e)
{
//...do some stuff
}
protected void rdoLabs_OnSelectedIndexChanged(object sender, EventArgs e)
{
//... reload
}
protected DbDataReader rdoGroups()
{
int group_type_id = GroupTypeId();
Group grp = new Group();
return grp.GetGroups(group_type_id);
}
protected DbDataReader rdoUserLabs()
{
RadioButtonList rdoGrp = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
int GroupId = Convert.ToInt32(rdoGrp.SelectedValue);
LabAbnormalReasons lar = new LabAbnormalReasons();
return lar.GetLabsList(GroupId);
}
protected void rdoPrimary_OnSelectedIndexChanged(object sender, EventArgs e)
{
Session["Save"] = ((RadioButtonList)sender).ID;
RadioButtonList rdoGroups = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
int UserId = Convert.ToInt32(Session["UserId"]);
int DocId = Convert.ToInt32(Session["DocId"]);
SubmitLab_Data(arrLstItems, arrOthers);
}
protected void GetSessionVars()
{
RadioButtonList rdoGroup = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoPrimary = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoPrimary");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
if (rdoGroup.SelectedIndex != -1)
{
Session["rdoGroup"] = (string)rdoGroup.SelectedValue;
}
if (rdoLabs.SelectedIndex != -1)
{
Session["rdoLabs"] = (string)rdoLabs.SelectedValue;
}
if (rdoPrimary.SelectedIndex != -1)
{
Session["rdoPrimary"] = (string)rdoPrimary.SelectedValue;
}
}
Here is example of user code:
THIS CODE NEVER FIRES BECAUSE the 3rd Button List data is not available here :
protected void Page_Load(object sender, EventArgs e)
{
/////*
//// * lab & Primary have been selected...
//// */
int lvl = SetLvlId();
int par_id = GetParentLvl();
Lab wuc = GetWuc(lvl);
if (wuc != null)
{
if (CommonUI.strTest(Convert.ToString(Session["rdoLabs"])) && CommonUI.strTest(Convert.ToString(Session["rdoPrimary"])))
{
// data in data base for this user, lab, doc identifier...
if (Convert.ToInt32(Session["rdoPrimary"]) > 0
{
// have user hdr data - see if item data is mapped...
// do some stuff here
}
}
}
}
I hope this is clear. I've att
---*--- Since original posting:
added simple javascript/OnDataBound
function Primary(object)
{
alert("Value Clicked :" + object);
}
protected void rdoPrimary_DataBound(object sender, EventArgs e)
{
RadioButtonList rdlPrimary = (RadioButtonList)sender;
foreach (ListItem li in rdlPrimary.Items)
{
li.Attributes.Add("onclick", "javascript:Primary('" + li.Value + "')");
}
}
Store and retrieve the values you want to retain in SaveViewState and LoadViewState methods and see if that works for you? Also look to the earlier and later lifecycle events for handling the logic - Init and OnPreRender. This has worked for me in the past.

Resources