How to reload GridView based on DropDownList selection dynamically - c#

I'm trying to load/reload a GridView based on the OnSelectedIndexChanged event of a DropDownList. The ddl has AutoPostBack set to true, but still the Grid won't load, unless I encapsulate it within an UpdatePanel. But once I do that, my FileUpload control stops working... What would be the best solution for this problem?
**Edit ** Relevant code:
aspx file
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="upProva" runat="server">
<ContentTemplate>
<%--user control for data selection--%>
<asp:DropDownList ID="ddlAula" runat="server" DataTextField="nmAula" DataValueField="idAula"
CssClass="medio" Enabled="false" AutoPostBack="true" OnSelectedIndexChanged="ddlAula_OnSelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="gvQuestoes" runat="server" AutoGenerateColumns="False" CssClass="gv"
AllowSorting="false" DataKeyNames="idQuestao" OnRowCommand="gvQuestao_RowCommand">
<Columns>
<%--(...)--%>
</Columns>
</asp:GridView>
<asp:Button ID="btnSalvar" runat="server" ToolTip="Salvar" CssClass="botao40 salv40"
OnClick="btnSalvar_Click" ValidationGroup="trabalho" />
<asp:FileUpload ID="fuAnexo" runat="server" CssClass="fileOriginal" />
</asp:Content>
codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnArquivo.OnClientClick = "document.getElementById('" + fuAnexo.ClientID + "').click(); return false;";
txtAnexo.Attributes.Add("onclick", "document.getElementById('" + fuAnexo.ClientID + "').click(); return false;");
fuAnexo.Attributes.Add("onchange", "document.getElementById('" + txtAnexo.ClientID + "').value = this.value;");
}
}
protected void ddlAula_OnSelectedIndexChanged(object sender, EventArgs e)
{
gvQuestoes.DataSource = Questao.CarregarPorAula(Int32.Parse(ddlAula.SelectedValue));
gvQuestoes.DataBind();
}
The DataSource/Databinding is correct (I know because I've added a button to the page, and used the same binding code on the Button _Click event and it works).

You need to rebind the gridview in OnSelectedIndexChanged event. Something like
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Do your processing logic
gridview1.DataSource = new_modified_datasource;
gridview1.DataBind();
}

I found a fairly simple (though not ideal in all cases) with PostBackTrigger:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="upProva" runat="server">
<ContentTemplate>
<%--user control for data selection--%>
<asp:DropDownList ID="ddlAula" runat="server" DataTextField="nmAula" DataValueField="idAula"
CssClass="medio" Enabled="false" AutoPostBack="true" OnSelectedIndexChanged="ddlAula_OnSelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="gvQuestoes" runat="server" AutoGenerateColumns="False" CssClass="gv"
AllowSorting="false" DataKeyNames="idQuestao" OnRowCommand="gvQuestao_RowCommand">
<Columns>
<%--(...)--%>
</Columns>
</asp:GridView>
<asp:FileUpload ID="fuAnexo" runat="server" CssClass="fileOriginal" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSalvar" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>

Nowhere in your code do you show how you populate ddlAula. So here is my answer: the Page_Load you've shown is abbreviated, and actually you are populating ddlAula there. Furthermore, you are doing it each time, rather than checking IsPostBack. Therefore by the time your eventhandler for ddlAula is hit, the list has been reset and the value you selected is no longer selected.
If my answer is correct, you need to add the check in Page_Load:
if (!IsPostBack)
{
//populate ddlAula
}

Related

Dropdownlist selected value is reset to first item

I have tried to look through many questions about the dropdownlist and still yet to resolve my issue.
I have a Dropdownlist and a Submit button. When Submit button is clicked after value selected, it should update the Label text with the selected value of the Dropdownlist. However, what happened was each time value is selected from dropdown, it refreshes the page and the value captured was the first item in dropdownlist. How do I capture the selected value correctly before it refreshes?
Am at wits end, not sure where went wrong.
*All items in dropdownlist are unique. No duplication.
My codes:
ASP.NET
<form id="form1" runat="server">
<asp:DropDownList ID="ddlCode" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCode_SelectedIndexChanged"/>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"/>
<asp:UpdateProgress ID="updProgress" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<img alt="progress" src="img/loading.gif"/><br /><h2>Loading...</h2>
</ProgressTemplate>
</asp:UpdateProgress>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Button ID="submitBtn" runat="server" cssclass="btn btn-success" OnClick="submitBtn_Click" Text="Submit"/>
<asp:Label ID="lblCode" runat="server"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlCode" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
</form>
Code behind
string ddlSelectedIndex = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//This is to load code into dropdownlist which works fine.
LoadCode();
}
}
protected void ddlCode_SelectedIndexChanged(object sender, EventArgs e)
{
ddlSelectedIndex =(ddlCode.Items[ddlCode.SelectedIndex].Text).Substring(0, 4);
}
protected void submitBtn_Click(object sender, EventArgs e)
{
lblCode.Text = ddlSelectedIndex;
}
Try it without the "AutoPostBack=True" on the DropDownList... the way your code is written, it causes the page to refresh any time the DropDownList value changes. What you want is a postback when submit is clicked.

How do I update only a panel on check changed?

<asp:UpdatePanel id="up1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:CheckBox ID="chkParent" runat="server" autopostback="true" OnCheckedChanged="chkParent_OnCheckedChanged" />
<asp:DataList ID="ChildList" runat="server" OnItemDataBound="ChildList_OnItemDataBound">
</ContentTemplate>
</asp:UpdatePanel>
protected void chkParent_OnCheckedChanged(object sender, EventArgs e)
{
this.ChildList.DataSource = this.ChildValues;
this.ChildList.DataBind();
}
On check changed of parent, child gets updated but the entire page also loads. Any way to avoid it?

How to update textbox onchange without postback?

Is there a way to update a textbox without using postback? I'd like to populate the txtDFS field with the value of (100 - txtStocked) after the user enters data in the txtStocked field.
The following code works, but it uses postback so the page refreshes. Is there a way to accomplish this without refreshing the page?
<asp:TextBox ID="txtStocked" runat="server" Width="75px" AutoPostBack="true" OnTextChanged="txtStocked_TextChanged"></asp:TextBox>
<asp:TextBox ID="txtDFS" runat="server" Width="75px"></asp:TextBox>
protected void txtStocked_TextChanged(object sender, EventArgs e)
{
int stocked = Convert.ToInt16(txtStocked.Text);
int dfs = (100 - stocked);
txtDFS.Text = dfs.ToString();
txtDFS.Text = txtStocked.Text;
}
Solved this by using an UpdatePanel. Here is the updated code:
<asp:ScriptManager ID="SCManager" runat="server" />
<asp:UpdatePanel ID="SCPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:TextBox ID="txtStocked" runat="server" Width="75px" autopostback="true" OnTextChanged="Update_Text"></asp:TextBox>
<asp:TextBox ID="txtDFS" runat="server" Width="75px" ReadOnly="True"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
protected void Update_Text(object sender, EventArgs e)
{
int stocked = Convert.ToInt16(txtStocked.Text);
int dfs = (100 - stocked);
txtDFS.Text = dfs.ToString();
SCPanel.Update();
}

Losing detailsview dropdownlist values after postback

I'm using a dropdownlist inside a detailsview and it populates well, but when I do a insert there is a postback so I'm trying to bind the DDL again but the values are lost somehow.
My aspx:
<asp:UpdatePanel ID="InsertPanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableHeaderRow SkinID="tableheaderrowSkin">
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell BackColor="DarkGray" BorderColor="DarkGray" BorderWidth="1" Width="300">
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="nFuturesId"
DataSourceID="FutureCommodityODS" DefaultMode="Insert" OnItemInserting="DetailsView1_ItemInserting"
SkinID="detailsviewSkin" OnItemInserted="DetailsView1_ItemInserted" EnableModelValidation="True">
<BrummerComp:SortableDropDownList ID="DropDownListFuturesInsert" runat="server" SkinID="BCdropdownlistSkin">
</BrummerComp:SortableDropDownList>
</asp:DetailsView>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
I populate the DDL in Page_Load:
protected new void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindDropDownList();
}
//DetailsView1.DataBind();
}
BindDropDownList:
private void BindDropDownList()
{
var paperFutureList = (List<PaperFutures>)DataManager.GetPaperFutures();
var ddl = (DropDownList)DetailsView1.FindControl("DropDownListFuturesInsert");
ddl.DataSource = paperFutureList;
ddl.DataValueField = "nFuturesID";
ddl.DataTextField = "ShortNameAndFutureNameAndFutureId";
ddl.DataBind();
}
The problem is when I do a insert in my detailsview the DDL is loses it's values. I have tried databind the detailsview but then the values won't load at all.
The method BindDropDownList works well in Page_Load the first time. Also tried putting the methodcall outside !IsPostBack to always populate it but that doesn't work either.
I have checked GetPaperFutures() and it works well every time, so the problem is somewhere else, but I can't find where.
I was facing the similar problem. Eventually, I have found the solution!
Just call the BindDropDownList() in Page_PreRender event.
It works successfully!

Radiobuttonlist event not always firing

I have a radiobuttonlist with a selectedindexchanged event that updates a search function. One of the items is specified in the aspx, and the others are appended databound items. No matter what I set as the default, that item will not fire the event. All other items will fire the event. Also, it seems that after the "dead" item is selected, the event won't fire at all.
How can I track down the error and correct? Here is current code.
EDIT: Sorry if the short version was misleading. I wasn't sure what to include. Here is the whole page.
All aspx:
<%# Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>
<%# Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
<h2>
<asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label></h2>
<table class="style1">
<tr>
<td style="width: 435px" valign="top">
<asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
<asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />
<br />
<asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
</asp:Panel>
<asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
<asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
<cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
ValueEntryFile="../ConfigFiles/SearchMSDS.config">
</cc1:SqlWhereBuilder>
<br />
<br />
</asp:Panel>
<cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
TargetControlID="pnlAdvSearch">
</cc2:CollapsiblePanelExtender>
</td>
<td valign="top">
<asp:Panel ID="pnlStatus" runat="server">
<asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
CausesValidation="True" Visible="True">
<asp:ListItem Selected="True">All</asp:ListItem>
</asp:RadioButtonList>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:UpdatePanel runat="server" ID="upd2">
<ContentTemplate>
<asp:Button ID="btnExport" runat="server" Text="Export Results"
OnClick="btnExport_Click1" UseSubmitBehavior="False" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
<ProgressTemplate>
<img src="../images/loading.gif" alt="Loading..." style="text-align: center" />
<asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
</asp:UpdateProgress>
<asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
<asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
<asp:BoundField DataField="Fire" HeaderText="Fire" visible="false" SortExpression="Fire" />
<asp:BoundField DataField="Reactivity" HeaderText="Reactivity" visible="false" SortExpression="Reactivity" />
<asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
</Columns>
<SelectedRowStyle BackColor="Yellow" />
</asp:GridView>
<asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="SELECT [ID]
,[ChemicalTitle]
,[Manufacturer]
,[UsageDept]
,[Notes]
,[Health]
,[Fire]
,[Reactivity]
,[DateUpdated]
FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<br />
</asp:Content>
And code-behind:
List<String> safeWords = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
pnlStatus.Visible = User.IsInRole("msds_Admin");
gridResults.DataKeyNames = new String[] { "id" };
txtSimpleSearch.Focus();
if (!IsPostBack)
{
safeWords.Add("delete");
safeWords.Add("insert");
safeWords.Add("update");
safeWords.Add("set");
safeWords.Add("exec");
safeWords.Add("N'");
sqlMSDS.SelectCommand += " Where status = 0 ";
Session["Sql"] = sqlMSDS.SelectCommand;
try
{
Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
}
catch (Exception)
{
Session["OriginalSQL"] = sqlMSDS.SelectCommand;
}
}
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";
if (btnSearch.Visible)
{
btnSearch_Click(null, null);
if (RadioButtonList1.SelectedValue != "All")
{
sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
}
else
{
//Somehow force the grid to research using no status parameter
sqlMSDS.SelectCommand = Session["Sql"].ToString();
}
}
else
{
btnRunAdvSearch_Click(null, null);
if (RadioButtonList1.SelectedValue != "All")
{
if (sqlMSDS.SelectCommand.Contains("Where"))
{
sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
}
else
{
sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
}
}
else
{
//Somehow force the grid to research using no status parameter
sqlMSDS.SelectCommand = Session["Sql"].ToString();
}
}
}
Here is what was happening to me and the fix.
I had a radiobuttonlist that was not in an update panel, but defined as a trigger for an update panel. I had onselectedindexchanged defined as well. Radiobuttonlist had the first listitem attribute selected="true", so it would be selected by default on page load. Then selecting the second listitem worked fine, posting back and updating the update panel.
However, selecting the first item again was not firing onselectedindexchanged event. Using Firefox's awesome Inspect Element utility, I was able to determine that the server was generating the html element (checked only on the first, default list item). But since the radiobuttonlist was not in the update panel, the checked="checked" attribute for the second item was never getting written to the browser, even though client-side the second radio button visually appeared to be selected. Therefore, when selecting the original item the second time, the onselectedindexchanged was not firing server-side, because the newly selected index was already indicated as selected in the POST event.
You won't see this problem if the list is inside the panel you want to refresh, because the postback causes the browser to receive "new" elements with the checked="checked" on the newly selected item. The layout of my page made it inconvenient to have these in the same panel, so the fix for me was to put the radiobuttonlist in it's own little update panel. Whichever works for you, the answer is to make sure the radiobuttonlist is in SOME update panel, so the checked attribute can be sent to the browser for each item when selected.
Does this RadioButtonList specified as AsyncPostBackTrigger for another UpdatePanel? If so, check following link: CheckedChanged event not firing on a radio button within UpdatePanel
I have reproduce that behaviour and fix this with the following script:
$(function () {
$("input[type='radio']:first", $("#<%= RadioButtonList1.ClientID %>")).attr("checked", true);
});
if you can't use the jQuery try this javascript:
window.onload = function () {
window.document.getElementById("<%= RadioButtonList1.ClientID %>_0").checked = true;
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClientScript.RegisterStartupScript(this.GetType(), "RadioButtonListDefaultValue", String.Format("window.document.getElementById('{0}_0').checked = true;", RadioButtonList1.ClientID), true);
}
}
As user user2965308 said, if the RadioButtonList is inside of the UpdatePanel this issue doesn't happen.
https://www.codeproject.com/Questions/118042/RadioButtonList-Postback-issue-when-selected-by-co
"Get it inside an update panel, with property "ChildrenAsTriggers" on true. This solve the issue for me."
<asp:ListItem Selected="True">All</asp:ListItem>
Clicking "All" doesn't change the selected index since that item was already selected, so the event does not fire. Picking any other option changes the selected option and causes the event to fire. I believe your goal is to display results for all statuses when you click on "All". You should do one of the following:
Display those results when the page initially loads since "All" is already selected.
Add a "Search" button that initiates the post-back instead of using the radio button's AutoPostBack.
Replace the RadioButtonList with a DropDownList, and give it two initial ListItems: "Pick a Status" - whose value is an empty string, and "All" whose value is "All". The "Pick a Status" dummy entry would look less out of place in a DropDownList than in a RadioButtonList.
Of the options listed above, I would personally prefer the "Search" button, because AutoPostBack annoys me as a user. I hate AutoPostBack DropDownLists that make the web page go bonkers when I accidentally use my mouse wheel when the list has focus.

Categories