Bug with asp.net controlid name - c#

Is there any naming convention or restrictions for a button to be named as "submit"? I have a dropdown list with autopostback= true and a button. It should auto generate textbox with the data from the database
<asp:DropDownList ID="d1" runat="server" DataSourceID="SqlDataSource1" DataTextField="scode" DataValueField="scode" OnSelectedIndexChanged="d1_SelectedIndexChanged" AppendDataBoundItems="true" AutoPostBack="true">
<asp:ListItem Selected="True">0</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [scode] FROM [warehouse]"></asp:SqlDataSource>
<asp:TextBox ID="t1" runat="server"></asp:TextBox>
<asp:Button ID="submit" runat="server" Text="Button" />
codebehind:
protected void d1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("hello");
t1.Text = "abcd";
}
my problem is when i set the controlid of my button as "submit" the postbacks and event handling from the dropdownlist are not triggered but pending. The postbacks and event handling are only triggered when i click on the "submit" button. Pretty sure the problem lies within controlid of the button as I took few hours of trial and error to find a workaround. By renaming the controlid of the button as "submit1" and everything worked perfectly. In short, the textbox are autogenerated with my data whenever I select an item when the controlid of the button is named as submit1". Meanwhile if the controlid of the button is "submit", the data are only generated when i click on the button. This is a small issue as i managed to find the workaround but i would like to know why is this happening.

Using the following minimal code I was able to reproduce your issue on a new web application project with no master page.
<asp:DropDownList runat="server" OnSelectedIndexChanged="d1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>0</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="ResultLabel" runat="server" />
<asp:Button ID="submit" runat="server" Text="Button" />
Code behind
protected void d1_SelectedIndexChanged(object sender, EventArgs e)
{
ResultLabel.Text = "Postback occurred";
}
If you watch the JavaScript console, you'll see that it results in an error when you change the dropdownlist selection.
Uncaught TypeError: theForm.submit is not a function
This error comes from the bit of code that Web Forms inserts into your page to make postbacks work properly.
That error prevents the postback from completing. The solution is to not have any controls with an ID of submit. You might consider this a bug, but changing the framework to get around this issue would make the framework more complicated than it needs to be.

Related

Databind fires after ItemUpdated event

I'm using an asp.net 4 web site project (C#) in VS2008 and I have a FormView with ItemUpdated event:
<asp:FormView ID="FormView1" runat="server" DataSourceID="ds1" OnItemUpdated="FormView1_ItemUpdated">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("col1") %>' />
</EditItemTemplate>
</asp:FormView>
protected void FormView1_ItemUpdated(object sender, EventArgs e)
{
FormView1.DataBind(); // adding this line even doesn't help
TextBox box = FormView1.FindControl("TextBox1") as TextBox;
box.Enabled = false;
}
But I can't figure out, why an extra "FormView1.DataBind()" or Render(?) happens AFTER the ItemUpdated event. The result is that my code in the ItemUpdated event gets like "overwritten" and the TextBox1 doesn't get disabled.
When I set a breakpoint to the last line "box.Enabled = false;" then I see that after the ItemUpdated event it jumps to the aspx page again and steps through the TextBoxes.
Disabling this TextBox1 from another GridView1_SelectedIndexChanged works fine.
Is there any way to see the "current lifecycle progress" in debugging?
EDIT:
To clarify the reasoning...
I have a GridView1 where selecting the item populates the abovementioned FormView1. The point is that I need to disable some of the TextBoxes in the FormView1 based on, for example, user access levels.
Selecting the item from GridView1 disables the TextBox1 just fine, but when I click the Update button on the FormView1 then all TextBoxes are enabled, even if I see in the debugger code running through the GridView1_SelectedIndexChanged() function. And after I re-select the gridview item, the correct TextBoxes are disabled again.
Using even this code:
<asp:FormView ID="FormView1" runat="server" DataSourceID="ds1" DefaultMode="Edit" OnItemUpdated="FormView1_ItemUpdated">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("col1") %>' />
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("col2") %>' />
<asp:Button ID="Btn1" runat="server" CommandName="Update" Text="Update" />
</EditItemTemplate>
</asp:FormView>
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (UserAccess() == false) {
TextBox box2 = FormView1.FindControl("TextBox2") as TextBox;
box2.Enabled = false;
}
}
protected void FormView1_ItemUpdated(object sender, EventArgs e)
{
GridView1_SelectedIndexChanged(sender, e);
}
Maybe I should disable my Textboxes via another event?
This doesn't make sense, please explain more about why you are trying to disable the TextBox, have you just left the ItemTemplate off in your question? or is it actually missing? if it's missing why?
The TextBox is in the FormView's EditItemTemplate, so will only be visible when the FormView is in edit mode. After clicking update or cancel the TextBox will no longer be rendered, and the ItemTemplate is rendered instead. So there should be no need to set the TextBox to be disabled.
EDIT
Ok since you edited your question. You need to use the OnDataBound event of the FormView, which occurs at the end of binding, and disable your TextBoxes at that point.
aspx
<asp:FormView ID="FormView1" runat="server" DataSourceID="ds1"
OnDataBound="FormView1_DataBound">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("col1") %>' />
</EditItemTemplate>
</asp:FormView>
aspx.cs
protected void FormView1_DataBound(object sender, EventARgs e)
{
if (UserAccess() == false) {
TextBox box2 = FormView1.FindControl("TextBox2") as TextBox;
box2.Enabled = false;
}
}
Rather then using gridview selected Index change you can use DataBound event on formview, so your logic would fire everytime the formview is rebind.

Session Variable in ASP.NET returns previous value in ModalBox?

I have a question regarding passing Session Variables to a text-box in an Update Panel (which is displayed in a Modal PopUp).
This is the code I have so far:
ASPX CODE:
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Link" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="panel_Load">
<ContentTemplate>
<asp:Button ID="OKButton" runat="server" Text="Close" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:ModalPopupExtender ID="mpe" runat="server" TargetControlID="ClientButton" PopupControlID="UpdatePanel1" OkControlID="OKButton">
</asp:ModalPopupExtender>
<asp:Button ID="ClientButton" runat="server" Text="Launch Modal Popup (Client)" style="display:none;" />
CODE BEHIND (C#):
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lbl_nme = (Label)clickedRow.FindControl("lbl_name");
String string_nme = lbl_nme.Text.ToString();
Session["Name"] = string_nme;
mpe.Show();
}
protected void panel_Load(object sender, EventArgs e)
{
Label1.Text = (string)(Session["Name"]);
}
So basically I have a GridView with name, address etc… When the user clicks on a link in a row, then the value for the name field of that row is saved as a session variable. Then a Modal PopUp is displayed. The Modal PopUp should then show the Name which was saved as a Session variable.
The code sort of works. What I’m experiencing is that when I click a row, the Label1.Text in the Modal PopUp is empty. So if I close the PopUp then click another link in another row, the PopUp then displays the Name of the row that was clicked previously.
In other words.. If row 1 has Name “Kevin” and row 2 has Name “Nathaniel”, and I click a link to open the Modal PopUp of row 1, I would expect the PopUp to display “Kevin”. But it doesn’t. The first time I click a link after rebuilding the application, nothing is displayed. But say I click row 2 after clicking row1, then the Modal PopUp displays the value of the row I clicked before, i.e. “Kevin” when I expect it to be “Nathaniel”.
I hope I didn’t confuse anyone. I’m a newbie and I’m just getting into this stuff, so I’d appreciate it if someone could help me out, preferably with examples of code etc.
Thank you. Much appreciated.
The "Load" event (panel_Load) occurs before the "Click" event (LinkButton1_Click) so it only sees the previous value.
The quick fix is to set the label in the "Click" event as well. Unless ViewState is enabled for the label (ick!) the label may have to be [re]set in the "Load" as well, depending upon when/how updates occur.
See ASP.NET Page Life Cycle Overview and ASP.NET Application and Page Life Cycle: Page Events.
Happy coding.

Value is not found in boundfield in gridview?

I am trying to assing value to hiddenfield on indexchange event of dropdownlist ! Actually the problem is when I am trying to update my record i can not find value of that hidden field ! Kindly give me solution or suggest any another option ! Thank You !
My grid view is
<asp:TemplateField HeaderText="LocCode" SortExpression="LocCode">
<EditItemTemplate>
<ajax:UpdatePanel ID="upEditsLocation" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddlLocation" runat="server"
DataSourceID="sdsLocation"
OnDataBound="ddlLocation_DataBound"
DataValueField="LocCode" AppendDataBoundItems="false"
DataTextField="LocCode"
AutoPostBack="true"
onselectedindexchanged="ddlLocation_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsLocation" runat="server" ConnectionString="<%$ ConnectionStrings:ccConnString %>"
ProviderName="<%$ ConnectionStrings:CCConnString.ProviderName %>" SelectCommand="Select LocCode from Location">
</asp:SqlDataSource>
</ContentTemplate>
</ajax:UpdatePanel>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%# Bind("LocCode") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
and my indexchange event is
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
hdloc.Value = ddlLocation.SelectedItem.Text;
}
And my hidden field is
<asp:HiddenField ID="hdloc" runat="server" />
From the code I can see the HiddenField is not part of your update panel. Hence if you assign any value to it, it will not reflect on client machine. Increase the scope of panel to include the hidden field, and then try.
OR you can try this solution from ASP.net Forum
Here is a small tutorial on update panel (MSDN)
Hope this helps you.
GridViewRow cancel = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)cancel.FindControl("lblid");
If you can't access hdloc from code behind, either is not added by Visual Studio on aspx.designer.cs (try delete it and add it back or change the id and then back to original value) or the hidden field is placed in other template of another binding control, which means you need to use ctrl.FindControl("hdloc") then cast to HiddenField.
Also you need to place this hidden field into an UpdatePanel with UpdateMode="Always".
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
hdloc.Value = (sender as DropDownList).SelectedItem.Text;
}
I'm sure that ddlLocation.SelectedItem.Text, like you use it, it gives a compilation error, because ddlLocation is not visible on code behind, since is inside of EditItemTemplate.

ASP.Net DataList problem

I have declaratively created a LinqDataSource and DataList and bound them in markup. I have created an ItemTemplate and Edit Template.
I have bound the DataLists oneditcommand and oncancelcommand to methods in the code behind.
<asp:DataList ID="MyDataList" runat="server" DataSourceID="LinqDataSource1" RepeatDirection="Horizontal"
Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False"
Font-Underline="False" HorizontalAlign="Center" RepeatColumns="4"
oneditcommand="MyDataList_EditCommand"
oncancelcommand="MyDataList_CancelCommand"
>
<ItemTemplate>
<div style="margin: 5px;">
<asp:LinkButton Text="Edit" CommandName="Edit" style="float:right" runat="server" />
// Other markup
</div>
</ItemTemplate>
When I click the LinkButton in the ItemTemplate, it runs the following code:
protected void DataList_EditCommand(object source, DataListCommandEventArgs e)
{
MyDataList.EditItemIndex = e.Item.ItemIndex;
MyDataList.DataBind();
}
This works fine and puts the selected item in the DataList into edit mode.
The Edit Template:
<EditItemTemplate>
<div style="margin: 5px;">
<asp:LinkButton Text="Cancel" style="float:right"
runat="server" CommandName="cancel" CausesValidation="false"/>
//other markup
</div>
</EditItemTemplate>
When I click the cancel button in the edit template, It does not fire the method in the code behind (the breakpoint doesn't get hit).
The Code that should be run when cancelling never get's run, so I can not exit the edit mode back into normal read mode:
protected void MyDataList_CancelCommand(object source, DataListCommandEventArgs e)
{
PhotoDataList.EditItemIndex = -1;
PhotoDataList.DataBind();
}
Can anyone think of a reason for this?
---- UPDATE
It seems that it is just the second firing of an event on the DataList that doesn't work, as I have know bound to the ItemCommand event, and was going to intercept the DataListCommandEventArgs.CommandName property and do something based on that. If you click the Edit link button, the ItemCommand method fires (with no code body at all), but the second time you click the edit link button, the ItemCommand method does not get hit.
The name of your DataList is : "MyDataList"
but Cancel event calls PhotoDataList!
protected void MyDataList_CancelCommand(object source, DataListCommandEventArgs e)
{
PhotoDataList.EditItemIndex = -1;
PhotoDataList.DataBind();
}
I can't duplicate your problem, I ran this demo code and all events and templates worked fine:
How to: Allow Users to Edit Items in DataList Web Server Controls
Do you have any errors in your event logs? Also, I don't see the DataKeyField defined, how are you selecting your data?

Bring up input form on same page with dropdownlist?

I'm brand new at this, using vs2010 with asp.net and c#, and I'm trying to use a button click event to display forms on my "Add Product" page (the forms will be textbox/label based for inputting data), using items from a dropdownlist of products. Which methods are available/is there a 'best practice' for this sort of thing? I've been fooling around with an if (Dropdownlist.SelectedIndexChanged) statement, but I'm not quite clear on why the syntax requires the SelectedIndexChanged method to preclude a += or -=. Thoughts?
The SelectedIndexChanged method has the += because you are adding an event handler to a specific elements event. Is the button you click on the Add Product page? If so for the OnClick event you could just set your form details based on the DropDownList SelectedItem or SelectedIndex. You may also need to wrap that panel in an UpdatePanel so that it can update visibility without reloading the whole page.
<asp:UpdatePanel ID="updateFormPanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblName" runat="server" Text="" />
<asp:TextBox ID="txtDetails" runat="server" Text="" />
//More TextBox's or whatever you want
</ContentTemplate>
</asp:UpdatePanel?
<asp:DropDownList ID="ddlProductCategory" runat="server" />
<asp:Button ID="btnAddProduct" runat="server" OnClick="AddProduct_Click" Text="Add Product" />
//Code File Behind
protected void AddProduct_Click(Object sender, EventArgs e)
{
lblName.Text = ddlProductCategory.SelectedItem.Text;
txtDetails.Text = ddlProductCategory.SelectedItem.Value;
}

Categories