Trigger Problem, Update Panel Does Not Work? - asp.net

I create dynamic LinkButton and I add LinkButton's Click Trigger to UpdatePanel.
Now, When I first click to any one of link button trigger is runing good and show my select whitout POSTBACK. After That, I click other LinkButton All Page Loading and POSTBACK running so Trigger Does Not Work!
What is the problem ? Please Help!
protected void Page_Load(object sender, EventArgs e)
{
ShowAllCar();
}
public void ShowAllCar()
{
dsAraclarTableAdapters.tblAraclarTableAdapter _t=new dsAraclarTableAdapters.tblAraclarTableAdapter();
dsAraclar.tblAraclarDataTable _m =_t.GetData();
int i=0;
UpdatePanel1.Triggers.Clear();
pnlAraclar.Controls.Clear();
foreach (DataRow _row in _m.Rows)
{
LinkButton _linkbutton =new LinkButton();
i++;
_linkbutton.ID ="Option" + i.ToString();
_linkbutton.Text = "<img src='" + _row["Resim"].ToString() + "' border='0'/> <b>" + _row["Marka"].ToString() + " " + _row["Model"].ToString() + "</b><br/>" + _row["Ozellikler"].ToString() + " : " + _row["KisFiyat"].ToString() + ":" + _row["YazFiyat"].ToString();
_linkbutton.CssClass="ContextMenuItem";
_linkbutton.PostBackUrl = "";
_linkbutton.Click +=new EventHandler(OnCarSelect);
pnlAraclar.Controls.Add(_linkbutton);
AsyncPostBackTrigger _trigger = new AsyncPostBackTrigger();
_trigger.ControlID = _linkbutton.ID;
_trigger.EventName = "Click";
UpdatePanel1.Triggers.Add(_trigger);
}
}
protected void OnCarSelect(object sender, EventArgs e)
{
lblSelection.Text = "You selected <b>" + ((LinkButton)sender).Text + "</b>.";
}

You need to add the controls back to the control tree earlier in the page life cycle:
PreInit Use this event for
the following:
...
* Create or re-create dynamic controls.
...
ASP.NET Page Life Cycle Overview

Related

ASP.NET UserControl get property in inline code

I have a user control, in the page load of the control I am doing this :
if (ViewState["Lib"] != null)
{
cfg.Lib = (string)ViewState["Lib"];
}
This Lib property can be modified with a textbox like this :
protected void Lib_e_Changed(object sender, EventArgs e)
{
cfg.Lib = Lib_e.Text;
ViewState["Lib"] = Lib_e.Text;
}
I have written the following javascript in my ascx file :
alert('<%= cfg.Lib %>');
It will always return the default value even if I have changed the text in my textbox. My textbox is in an update panel and I have set AutoPostBack to true. Is there something I am missing to update my value ?
It is happening because aspx page render
alert('<%= cfg.Lib %>');
before any assign you are performing on
cfg.Lib
to make it workable what you can do is .. register the script from server side like
protected void Lib_e_Changed(object sender, EventArgs e)
{
cfg.Lib = Lib_e.Text;
ViewState["Lib"] = Lib_e.Text;
ScriptManager.RegisterStartupScript(updatePanelId, updatePanelId.GetType(), "AnyKey", "alert('" + cfg.Lib + "')", true);
//ScriptManager.RegisterStartupScript(this, this.GetType(), "AnyKey", "alert('" + cfg.Lib + "')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(),"AnyKey","alert('"+cfg.Lib +"')",true);
}

Dynamically adding a commandbutton in ASP.NET

I have a page with a dynamically created command button.
I need to dynamically wire up a click event so I can grab the CommandArgument of the clicked button.
Button b = new Button();
b.ID = "btnTrigger2";
b.CssClass = "hiddenBtn";
b.CommandName = "lbl3";
b.Click += new EventHandler(btnTrigger_Click);
The problem is the last line - I can't wire up an EventHandler this way - I need to use the standard EventArgs instead of CommandEventArgs.
Anyone have any suggestions on getting this to work? There's got to be a way...
EDIT
Figured I'd post the code that finally worked in case anyone else tries to do the same thing.
`string tabLoadedScript = string.Empty;
string postBackScript = string.Empty;
string script = " <script language='javascript' type='text/javascript'>" + System.Environment.NewLine;
script += "function clientActiveTabChanged(sender, args) {" + System.Environment.NewLine;
int i = 0;
foreach(TabPanel tp in tc1.Tabs)
{
Button b = new Button();
b.ID = "btn" + tp.ClientID;
b.CssClass = "hiddenBtn";
b.CommandName = tp.ID;
b.Command += btnTrigger_Click;
this.form1.Controls.Add(b);
AsyncPostBackTrigger trg = new AsyncPostBackTrigger();
trg.ControlID = "btn" + tp.ClientID;
tabLoadedScript += "var isTab" + tp.ClientID + "loaded=$get('" + tp.Controls[0].ClientID + "');" + System.Environment.NewLine;
postBackScript += "if(!isTab" + tp.ClientID + "loaded && sender.get_activeTabIndex() == " + i + ") {" + System.Environment.NewLine;
postBackScript += "__doPostBack('" + b.ClientID + "','');}" + System.Environment.NewLine;
i++;
}
script += tabLoadedScript;
script += postBackScript;
script += "}" + System.Environment.NewLine;
script += "</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "cs", script, false);
protected void btnTrigger_Click(object sender, CommandEventArgs e)
{
System.Threading.Thread.Sleep(2500);
Panel ctrl = (Panel) FindControlRecursive(this, "pnl" + e.CommandName);
ctrl.Visible = true;
}
public static Control FindControlRecursive(Control Root, string Id)
{
if(Root.ID == Id)
return Root;
foreach(Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if(FoundCtl != null)
return FoundCtl;
}
return null;
}
`
You can still access the CommandArgument using the the first argument passed to the click handler.
Something like:
protected void btnTrigger_Click(object sender, EventArgs e)
{
Button btnTrigger = sender as Button;
String commandArgument = btnTrigger.CommandArgument;
.
.
.
.
//Other code....
}
You need to use the Command event instead of the Click event. Also, assuming you're using a recent version of Visual Studio and .Net, you can simply change the event registration from
b.Click += new EventHandler(btnTrigger_Click);
to
b.Command += btnTrigger_Click
The explicit typing of the delegate is redundant and will be inferred by the compiler. You can now change the signature of your event handler to:
protected void btnTrigger_Click(object sender, CommandEventArgs e)
And the code should work as desired.
Unfortunately, the default code snippets in Visual Studio still generate this old-style event listener code.

changing color of particular link button

i am using a series of linkbuttons A-z which are dynamically created what i want on the click of each its text color change to something else to make it different from others what i am doing
protected void Page_Init(object sender, EventArgs e)
{
// Adding Dynamically linkbuttons for all alphabets(i.e. A-Z)
for (char asciiValue = 'A'; asciiValue <= 'Z'; asciiValue++)
{
LinkButton lbtnCharacter = new LinkButton();
lbtnCharacter.ID = "lbtnCharacter" + asciiValue;
divAlphabets.Controls.Add(lbtnCharacter);
lbtnCharacter.Text = Convert.ToString(asciiValue);
lbtnCharacter.CssClass = "firstCharacter";
lbtnCharacter.ToolTip = "Show users whose name starts with '" + Convert.ToString(asciiValue) + "'";
lbtnCharacter.CommandArgument = Convert.ToString(asciiValue);
lbtnCharacter.Command += new CommandEventHandler(lbtnCharacter_Command);
}
}
void lbtnCharacter_Command(object sender, CommandEventArgs e)
{
ViewState["Selected_Character"] = e.CommandArgument;
LinkButton lbtn = (LinkButton)divAlphabets.FindControl("lbtnCharacter" + e.CommandArgument);
lbtn.ForeColor = System.Drawing.Color.Orange;
txtNameFilter.Text = string.Empty;
BindUserList();
}
it is working fine but on clicking more then one buttons all the buttons which are clicked changes their color to orange but what i want is whichever button i click only that button color should change on click of next button previous button should go to default state is this approach right or tell me if it can be achieved by css
Your problem is that the ViewState of the linkbuttons is being saved just before the controls are rendered, including the updated styling. Then, on your postback, after Page_Init, the ViewState is re-applied to each control, with the orange styling. This overrides the setting that you add in Page_Init. So in Page_Load, you need to reset the styling on each of the controls.
Add another style to your stylesheet
.highlighted { color:orange; }
In lbtnCharacter_Command, replace
lbtn.ForeColor = System.Drawing.Color.Orange;
with
lbtn.CssClass = "firstCharacter highlighted ";
In Page_Load, add:
foreach (var ctrl in divAlphabets.Controls)
{
if (ctrl is LinkButton)
((LinkButton)ctrl).CssClass = "firstCharacter";
}
On each Page_Load, all of the linkbuttons css class will be reset to the default. This is after the ViewState has been applied to them (between PageInit and PageLoad). Then on the Command event, the clicked button will have the new style appended. The color setting in this style will override whatever color setting is in the firstCharacter style.
UPDATE
protected void Page_Init(object sender, EventArgs e) {
for (char asciiValue = 'A'; asciiValue <= 'Z'; asciiValue++) {
var lbtnCharacter = new LinkButton {
ID = "lbtnCharacter" + asciiValue,
Text = Convert.ToString(asciiValue),
ToolTip = "Show users whose name starts with '" + Convert.ToString(asciiValue) + "'",
CommandArgument = Convert.ToString(asciiValue)
};
lbtnCharacter.Command += lbtnCharacter_Command;
divAlphabets.Controls.Add(lbtnCharacter);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CurrentLetter"] != null) {
foreach (var ctrl in divAlphabets.Controls) {
if (ctrl is LinkButton) {
if (((LinkButton) ctrl).Text == Session["CurrentLetter"].ToString()) {
((LinkButton) ctrl).CssClass = "firstCharacter highlighted";
}
}
}
}
}
void lbtnCharacter_Command(object sender, CommandEventArgs e) {
//Reset all of the other buttons only when clicking a new one
foreach (var ctrl in divAlphabets.Controls) {
if (ctrl is LinkButton) {
((LinkButton) ctrl).CssClass = "firstCharacter";
}
}
//Set the clicked button and save the Session state
var lbtn = (LinkButton)divAlphabets.FindControl("lbtnCharacter" + e.CommandArgument);
lbtn.CssClass = "firstCharacter highlighted";
Session["CurrentLetter"] = lbtn.Text;
}

Get selected Value from dropdownlist after submit?

I populate DropDownList in ASP.NET webforms:
<asp:DropDownList runat="server" ID="salesman"></asp:DropDownList>
users= Buslayer.GetSalesRep();
foreach (userentity user in users)
{
salesman.Items.Add(new ListItem(user.FirstName + " " + user.LastName,
user.UserID.ToString()));
}
After submission, I am still getting selected index = 0,
I tried all of this but failed:
Response.Write("" + salesman.SelectedValue);
Response.Write("" + salesman.SelectedItem.Value);
Response.Write("" + salesman.SelectedIndex);
Are you checking for the Page posting back with you databind?
Your page load should look something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
// Get your data
ddl.DataSource = yourData;
ddl.DataBind();
}

Dynamically Loaded ListButton's and PostBack Event

I am trying to get a dynamically loaded LinkButton to fire a postback event, which I then handle.
I have across Command, CommandName and CommandArgument - which looked real useful.. So I started messing with that, but currently cannot get to work as desired.
The links are rendered within a table that is created on the fly, here is the code to generate them:
// The links are stored in Session since I was told that the objects need to remain intact across requests.
LinkButton GetEditCardLink(string card)
{
if (!IsPostBack)
{
TW("Creating Link for Card '" + card + "' and Placing in Session.", true);
LinkButton link = CreateEditLink(card);
Business.Session.Set<LinkButton>("LinkedCards_EditLink_" + card, link);
}
return Business.Session.Get<LinkButton>("LinkedCards_EditLink_" + card);
}
// Here the link itself is created, note the ID and Command details are set.
LinkButton CreateEditLink(string forCard)
{
TW("Setting Up Link for Card: " + forCard, true);
LinkButton rtn = new LinkButton();
rtn.ID = "Edit_" + forCard;
rtn.Text = Resources.Header("EditDetails");
rtn.CommandName = "Edit";
rtn.CommandArgument = forCard;
rtn.Command += new CommandEventHandler(RedirectToEdit);
rtn.Attributes["style"] = "display: block; text-align:center;";
return rtn;
}
// ... And the delegate I want called on PostBack..
void RedirectToEdit(object sender, CommandEventArgs e)
{
TW("RedirectToEdit Called:\r\nName: " + e.CommandName + "\r\nArgument: " + e.CommandArgument);
}
Trace confirms that the LinkButtons are being loaded correctly, and are only being creating once, so in theory they should be fine, but when I click the link, a PostBack is performed, but the RedirectToEdit method is not called?
All help gratefully received! :)
NOTE
Oh, I thought I should mention TW is just a utility method for Trace.Write/Warn :)
When you create a control that needs event handling you have to do it early enough in the processing that the event handler gets hooked up. Override OnInit for the page where you are creating the table and move the table creation code there. As #ScarletGarden suggests, you also need to add the control whether it's a PostBack or not. I believe that doing it in Page_Load is too late for the event to be detected if you add the control there.
Reference
Here is my trial, and it worked :
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
//{
placeHolderAtPage.Controls.Add(CreateEditLink("forCard1"));
//}
}
LinkButton CreateEditLink(string forCard)
{
LinkButton rtn = new LinkButton();
rtn.ID = "Edit_" + forCard;
rtn.Text = "EditDetails";
rtn.CommandName = "Edit";
rtn.CommandArgument = forCard;
rtn.Command += new CommandEventHandler(RedirectToEdit);
rtn.Attributes["style"] = "display: block; text-align:center;";
return rtn;
}
void RedirectToEdit(object sender, CommandEventArgs e)
{
Response.Write("RedirectToEdit Called:\r\nName: " + e.CommandName + "\r\nArgument: " + e.CommandArgument);
}
If you decomment the IsPostBack line, RedirectToEdit will be useless.
Only binding codes can be under IsPostBack control.

Resources