Trouble with dynamic generated rows in a table in ASP.NET - c#

I have a table which I need to populate with some results, based on what I select. While the table itself is already present, the rows need to be generated dynamically. I have found posts which help me create the rows and preserve them upon a page refresh, but my problem now is that when I try to repopulate the table upon a refresh, the table itself is seen as null.
This here is the front end, where given the selected items and if generate MZA is unchecked, then a list of excels needs to be made in the table.
<div class="jumbotron" Style="width:1200px; margin-top:-50px">
<div class="panou_raport1">
<p class="lead2">Selectați DRDP-ul :</p>
<asp:DropDownList ID="ddl_select_drdp" runat="server" ToolTip="Selectați DRDP" OnSelectedIndexChanged="Schimba_DRDP" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">Selectați judetul:</p>
<asp:DropDownList ID="ddl_select_judet" runat="server" ToolTip="Selectați judet" OnSelectedIndexChanged="Schimba_Judet" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">Selectați categorie drum :</p>
<asp:CheckBoxList ID="chbx_catDrum" runat="server" ToolTip="Selectați categorie" OnSelectedIndexChanged="Schimba_Categorie" RepeatDirection="Horizontal" AutoPostBack="true" CssClass="DRDP1" Width="75%">
<asp:ListItem>DN</asp:ListItem>
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>VO</asp:ListItem>
<asp:ListItem>DJ</asp:ListItem>
<asp:ListItem>DC</asp:ListItem>
</asp:CheckBoxList>
<p class="lead2">Selectați post:</p>
<asp:DropDownList ID="ddl_select_post" runat="server" ToolTip="Selectați post" OnSelectedIndexChanged="Schimba_Post" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">Selectați data:</p>
<asp:DropDownList ID="ddl_select_data" runat="server" ToolTip="Selectați data" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">MZA</p>
<asp:CheckBoxList ID="chbx_MZA" runat="server" ToolTip="Bifati MZA" OnSelectedIndexChanged="Verifica_MZA" RepeatDirection="Horizontal" AutoPostBack="true" CssClass="DRDP1" Width="75%">
<asp:ListItem Selected="True">Genereaza MZA</asp:ListItem>
</asp:CheckBoxList>
<div class="viabil_rap">
<asp:Button ID="btn_lista_excel" runat="server" OnClick="btn_genereaza_Click" text="Genereaza" CssClass="buton1" Visible="false" UseSubmitBehavior="False" Style="margin-top:40px"/>
</div>
<div class="mza_excel">
<asp:ImageButton ID="img_export_excel" ImageUrl="Content/images/excel.png" CssClass="img_excel" runat="server" OnClick="btn_MZA_Click" UseSubmitBehavior="False" />
</div>
<div class="excel_descarca">
<asp:Button ID="DownloadSelected" runat="server" OnClick="Descarca_Excel_Click" text="Descarca" CssClass="buton1" UseSubmitBehavior="false" Visible ="False" style="margin-top: 50px; margin-bottom: 20px"/>
</div>
</div>
<br/>
<div class="panou_raspuns1">
<div class="datagrid2" style="overflow-y: auto; overflow-x: auto;">
<asp:Table ID="tbl_excel_recensamant" runat="server" GridLines="Both" CssClass="Table1" Width="600px">
<asp:TableRow ID="row_excel_recensamant" runat="server" HorizontalAlign="Center">
<asp:TableCell runat="server" style="color:white; width:3%; background-color:#567bb7; font-size:16px;">Selectează</asp:TableCell>
<asp:TableCell runat="server" style="color:white; width:8%; background-color:#567bb7; font-size:16px;">Data inspectii</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</div>
</div>
This here is the backend. In here I try to recreate the generated rows (which are a checkbox with an excel download btn and a date) in the Page_PreInit. The function that creates the rows themselves is CreateCheckBox(), while btn_genereaza_Click() first creates the table with its rows, and gives each Checkbox an ID, which is stored in a list so I can then check which checkboxes have been checked. Problem is, when clicking the Download btn after the table with the results is first made, it empties the table values even if the checkboxes and excel btns are still displayed (like the checkbox ID), hence why I need the PreInit. But as it gets to that, in the CreateCheckBox() when called a second time, from within Page_PreInit, the table itself, which is defined in the front end, is null. What am I doing wrong?
List<string> ID_Checkbox = new List<string>();
List<string> ID_Checked = new List<string>();
List<string> Excel_list = new List<string>();
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("ChBx")).ToList();
foreach (string key in keys)
{
string chbx_id = key.Replace("ctl00$MainContent$", string.Empty);
string img_id = key.Replace("ctl00$MainContent$ChBx", string.Empty);
CreateCheckBox(chbx_id, img_id);
}
}
protected void btn_genereaza_Click(object sender, EventArgs e)
{
//code that checks all selected options and runs a SELECT
SqlDataReader rd = cmd.ExecuteReader();
List<string> lista_genertate = new List<string>();
if (rd.HasRows)
{
string data_raport = "";
while (rd.Read())
{
data_raport = rd[rd.GetOrdinal("DataRaport")].ToString().Split(' ')[0];
string id_chbx = "ChBx" + data_raport;
lista_genertate.Add(id_chbx);
CreateCheckBox(id_chbx, data_raport);
}
DownloadSelected.Visible = true;
btn_lista_excel.Visible = false;
}
rd.Close();
conn.Close();
Session["lista_excel"] = lista_genertate;
}
private void CreateCheckBox(string id_chbx, string id_img)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
cell1.HorizontalAlign = HorizontalAlign.Center;
cell2.HorizontalAlign = HorizontalAlign.Center;
cell2.Text = id_img;
//Checkbox for each Excel
CheckBox cb = new CheckBox();
cb.Checked = false;
cb.ID = id_chbx;
cb.AutoPostBack = false;
cell1.Controls.Add(cb);
ID_Checkbox.Add(cb.ID);
cell1.Controls.Add(new LiteralControl(" "));
ImageButton img_select_excel = new ImageButton();
img_select_excel.ImageUrl = "Content/images/excel.png";
img_select_excel.Height = Unit.Pixel(30);
img_select_excel.Width = Unit.Pixel(30);
img_select_excel.ID = id_img;
img_select_excel.Click += new ImageClickEventHandler(btn_excel_Click);
cell1.Controls.Add(img_select_excel);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
tbl_excel_recensamant.Rows.Add(row); //HERE IS WHERE IT CRASHES, since it sees the table itself as null
tbl_excel_recensamant.HorizontalAlign = HorizontalAlign.Center;
}

Related

Changing a gridview's datasource based on dropdownlist

I'm struggling a lot and I hope someone can help me please.
I have a 4 dropdownlists, a search button and a normal gridview with a basic SQLdataConnection.
The SQLdataConnection is a stored procedure that retrieves 3 tables based on 4 parameters. These 3 tables are then joined together into the gridview.
BUT
One of the dropdownlists has the options of Total, Fast and Slow. So based on which option the user chooses the respective table should be loaded into the gridview when the search button is pressed. (So if total is chosen, the total table should be loaded into the gridview)
I don't know if the SQLdataConnection should be changed with each option to show only the appropriate table.
Below is a copy of the html of the dropdowns and gridview as well as the code behind.
<tr>
<td style="text-align: right" class="pad-right-0">
<asp:DropDownList ID="selSeconds" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selHours" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selMerchantId" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selTableType" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:Button ID="btnSearch" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" OnClick="btnSearch_Click" Text="<%$Resources:Resource, btnSearch %>" />
<asp:ImageButton ID="btnExportToExcel" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" onclick="btnExportToExcel_Click" Text="Export to excel" ImageUrl="images/Excel.png" AlternateText="<%$Resources:Resource, lblExportExcel %>"
CausesValidation="false" />
<asp:RequiredFieldValidator ID="rqrdMerchantId" runat="server" ErrorMessage="<%$Resources:Resource, lblRequired %>" ControlToValidate="selMerchantId" ForeColor="Red" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnMerchantId" runat="server" Value="0" />
<asp:GridView ID="gridSpeedAnalysis" runat="server" DataSourceID="gridSqlConnection">
</asp:GridView>
<asp:SqlDataSource ID="gridSqlConnection" runat="server"></asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] == null || Session["UserType"] == null)
{
Response.Redirect("Login.aspx");
}
LoadDropDowns();
}
private void LoadDropDowns()
{
System.Web.UI.WebControls.ListItem item;
selSeconds.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select Second", "0"));
int index = 1;
for (int Second = 0; Second <= 10; Second++)
{
System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(Second.ToString(), Second.ToString());
selSeconds.Items.Insert(index, li);
index++;
}
item = selSeconds.Items.FindByValue(DateTime.Now.Year.ToString());
selSeconds.SelectedIndex = selSeconds.Items.IndexOf(item);
if (Session["UserType"] != null && (Session["UserType"].ToString().ToLower() == "System Administrator".ToLower()))
{
selMerchantId.DataSource = BOL.MerchantGroup.Load();
selMerchantId.DataTextField = "Description";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = "0", Text = "Select Group" });
rqrdMerchantId.InitialValue = "0";
}
else if (Session["UserType"].ToString().ToLower() == "Head Office".ToLower())
{
BOL.MerchantGroup group = new BOL.MerchantGroup(int.Parse(hdnMerchantId.Value));
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = hdnMerchantId.Value, Text = group.Description });
}
DataTable dt = BOL.Merchant.GetDropdownByMerhcantGroupId(int.Parse(Session["MerchantGroupId"].ToString()));
selMerchantId.DataSource = dt;
selMerchantId.DataTextField = "Name";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Total"});
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Fast" });
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Slow" });
}
protected void btnSearch_Click(object sender, EventArgs e)
{
}

Asp .NET Making a value Check on a drop down list from a nother drop down list

I want to force the user to change the selection of the first drop down list IF he/she selected a particular value in the second drop down list.
<asp:DropDownList ID="ddlGxP" runat="server" CssClass="stdDropdownSmall" OnSelectedIndexChanged="ddlGxP_SelectedIndexChanged" AutoPostBack="true" />
<
else
{
}
The above is the first drop down list where the user should select value from "ddlGxP"
The following is the second drop down list where I need to make the check when the user make a selection, I have to check on the first drop down.
<div class="divStandard">
<asp:Label ID="Label23" runat="server" CssClass="stdLabel">nalized Method <span class="mandatory"> *</span></asp:Label>
<asp:DropDownList ID="ddlFinalizedMethod" runat="server" CssClass="stdDropdown" />
<asp:CustomValidator ID="cvFinalizedMethod" runat="server" ControlToValidate="ddlFinalizedMethod" InitialValue="0" OnServerValidate="cvFinalizedMethod_ServerValidate"
CssClass="RequiredFieldError" ErrorMessage=" ! Please select another GxP Standard" />
} else {
<asp:TextBox ID="txtFinalizedMethodDisabled" runat="server" CssClass="stdTextboxSmallDisabled" Enabled="false" />
}
</div>
i don't have enough reputation so here is my comment.
i just want to clarify the problem in basic terms.
your design view consists of two dropdownlists.
you make a selection on dropdownlist1, its selectedindexchanged is triggered performing some sort of action.
you now make a selection on dropdownlist2, its selectedindexchanged is triggered and performs some sort of manipulation on dropdownlist1, either changing its contents or selected value;
SORRY FOR THE WAIT, I MADE SOME SIMPLE ERRORS DUE TO FORGETTING SOME THINGS;
The ANSWER!!!!
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
onselectedindexchanged="ddl2_selectindexchange">
</asp:DropDownList>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> str = new List<string>();
str.Add("red");
str.Add("blue");
str.Add("black");
List<string> str2 = new List<string>();
str2.Add("red");
str2.Add("blue");
str2.Add("black");
DropDownList1.DataSource = null;
DropDownList1.DataSource = str;
DropDownList1.DataBind();
DropDownList2.DataSource = null;
DropDownList2.DataSource = str2;
DropDownList2.DataBind();
}
}
protected void ddl2_selectindexchange(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
ddl = sender as DropDownList;
ListItem li = new ListItem();
li = ddl.SelectedItem;
string s = li.Text;
Label1.Text = s;
}

ASP.NET How to bind data in DropDownList outside GridView?

I am creating a web aplication to access data in a SQL Server 2008 database. I show the data in a Gridview and I can succesfully edit the rows (even with DropDownLists), but I want to implement the edit of those records with a modal dialog/popup using Bootstrap.
However, I can not get working these DropDownLists in this modal, because resides in a DIV outside the <asp:GridView> element. I can bind others text fields in the modal dialog, with this code (the modal dialog is fired with a command ) [code_behind]:
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtRUT.Text = HttpUtility.HtmlDecode(gvrow.Cells[2].Text);//.ToString();
txtDIGITO.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text);
txtCOD_FISA.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);
txtNOMBRE.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
//ddlCARGO is the DropDownList
ddlCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text);
lblResult.Visible = false;
//I know that the DropDownList ist outside the GridView, but i don't know how to access/bind data to it
DropDownList combo_cargo = GridView2.Rows[index].FindControl("ddlCARGO") as DropDownList;
if (combo_cargo != null)
{
combo_cargo.DataSource = DataAccess.GetAllCargos(); //in GridView default edit mode, this works OK
combo_cargo.DataTextField = "cargo";
combo_cargo.DataValueField = "idCARGO";
combo_cargo.DataBind();
}
combo_cargo.SelectedValue = Convert.ToString(HttpUtility.HtmlDecode(gvrow.Cells[6].Text));
}
The modal html code [.aspx]:
<!-- EDIT Modal Starts here -->
<div id="editModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="editModalLabel">Editar Empleado</h3>
</div>
<asp:UpdatePanel ID="upEdit" runat="server">
<ContentTemplate>
<div class="modal-body">
<p> Nombre: <asp:TextBox ID="txtNOMBRE" runat="server" columns="40"></asp:TextBox> </p>
<p>RUT: <asp:TextBox ID="txtRUT" runat="server" columns="8"></asp:TextBox> -
<asp:TextBox ID="txtDIGITO" runat="server" columns="1"></asp:TextBox></p>
<p>Código Fisa: <asp:TextBox ID="txtCOD_FISA" runat="server" columns="7"></asp:TextBox></p>
<%--<p>Cargo: <asp:TextBox ID="txtCARGO" runat="server" columns="7"></asp:TextBox></p>--%>
<p>Cargo: <asp:DropDownList ID="ddlCARGO" runat="server"></asp:DropDownList></p>
<%-- <p>Estado: <asp:TemplateField HeaderText="ESTADO" SortExpression="idESTADO">
<EditItemTemplate>
<asp:DropDownList ID="ddlESTADO" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblESTADO" runat="server" Text='<%# Bind("ESTADO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField> </p> --%>
</div>
<div class="modal-footer">
<asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label>
<asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" />
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView2" EventName="RowCommand" />
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
<!-- Edit Modal Ends here -->
I can give you an idea.
Create a DIV/user control with those controls that you need to edit.
On ROW click - open the DIV in model (jq you can use) and then either pass the Row content to the Model.open Or pass some unique ID of that ROW and load again from DB the Row corresponding detail. And allow editing there and on Save over there - saving to DB with that unique ID preserved.
Let us know
Finally I have found the solution:
Modal html (.aspx):
<div class="form-group">
<asp:TextBox ID="txtCARGO" runat="server" CssClass="hiddencol"></asp:TextBox> <%--data value field (hidden with CSS)--%>
<label class="col-xs-3 control-label" for="editModalCargo">Cargo</label>
<div class="col-xs-3 input_medio">
<asp:DropDownList id="editModalCargo" runat="server" name="editModalCargo" class="form-control input-md"/> <%--data text field--%>
</div>
</div>
<div class="form-group hiddencol"> <%--field with row id (hidden with CSS)--%>
<asp:TextBox ID="txtID" runat="server" columns="2"></asp:TextBox>
</div>
I've put OnRowCommand="GridView2_RowCommand" on <asp:GridView> and created a <asp:ButtonField> with CommandName="editRecord"> to edit the row.
Code behind (.aspx.cs):
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtID.Text = HttpUtility.HtmlDecode(gvrow.Cells[17].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtID">
txtCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[13].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtCARGO">
lblResult.Visible = false;
BindEditCargo(txtCARGO.Text);
}
}
private void BindEditCargo(string cargoValue) //Populates <asp:DropDownList id="editModalCargo">
{
editModalCargo.DataSource = DataAccess.GetAllCargos();
editModalCargo.DataTextField = "cargo";
editModalCargo.DataValueField = "idCARGO";
// Bind the data to the control.
editModalCargo.DataBind();
// Set the default selected item, if desired.
editModalCargo.SelectedValue = cargoValue;
}
DataAccess.cs:
public static DataTable GetAllCargos()
{
DataTable dt = new DataTable();
string sql = #"SELECT * FROM CARGO";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BRconn"].ToString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
return dt;
}
To read the value from modal (to pass it to a Update query for example), you can use (in code behind):
protected void btnSave_Click(object sender, EventArgs e) // Handles Update Button Click Event
{
int idEMPLEADO = Convert.ToInt32(txtID.Text); //Read value from <asp:TextBox ID="txtID">
int idCARGO = Convert.ToInt32(editModalCargo.SelectedValue); //Read value from <asp:DropDownList id="editModalCargo">
DataAccess.UpdateEmpleado(idEMPLEADO, idCARGO); //Update Query
BindData(); //Refresh Gridview
}

Dropdownlist inside Updatepanel not working Properly

i put 2 Dropdownlist inside a updatepanel. whenever 1st dropdownlist selected index changes 2nd dropdownlist's item changes.(like Country-State.. here in my case its city-area).
Whenever i change 1st dropdownlist(DDLCity1) selectedindex no problem, it works fine. But Two times only.
suppose, after page load i select "LA" no problem, area of LA will load in another dropdownlist DDLArea1. then i nake change, select "NY" city, again another dropdownlist will works fine.
BUT NOW ON THERD ATTEMPT MY 2ND DROPDOWNLIST SHOW NO CHANGES!!!!! IT sTILL SHOW LAST RESULT.
IN SORT, postback works only 2 times.
for testing i put a alert msg on indexchange of dropdown it popups only 2 times. seems like postback only 2 times :(( plzz help me;
<pre>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ViewStateMode="Enabled" UpdateMode="Always">
<ContentTemplate>
<asp:DropDownList ID="DDLCity1" runat="server" AutoPostBack="false" OnSelectedIndexChanged="DDLCity_SelectedIndexChanged"
ViewStateMode="Enabled">
<asp:ListItem Text="- All City -" />
</asp:DropDownList>
<asp:DropDownList ID="DDLArea1" runat="server" Style="margin-bottom: 0px" OnSelectedIndexChanged="DDLArea_SelectedIndexChanged"
AutoPostBack="false" ViewStateMode="Enabled">
<asp:ListItem Text="- Anywhere -" />
</asp:DropDownList>
<span style="position: absolute;">
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<img src="img/loading.gif" alt="Alternate Text" />
</ProgressTemplate>
</asp:UpdateProgress>
</span>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DDLCity1" EventName="SelectedIndexChanged" />
</Triggers>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DDLArea1" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<code>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DDLCity1.DataSource = objsql.GetTable("select distinct city from tblCity where status=1 order by city");
DDLCity1.DataTextField = "city";
DDLCity1.DataValueField = "city";
DDLCity1.DataBind();
DDLCity1.Items.Insert(0, new ListItem("- All India -", "- All India -"));
if (Request.Cookies["ddCityCookie"] != null)
{
ddlCity.SelectedIndex = int.Parse(Request.Cookies["ddCityCookie"].Value);
if (Request.Cookies["ddAreaCookie"] != null)
{
ddlArea.SelectedIndex = int.Parse(Request.Cookies["ddAreaCookie"].Value);
}
}
}
protected void DDLCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownCityIndexChange();
DDLArea1.SelectedIndex = 0;
}
protected void DDLArea_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie ddAreaCookie = new HttpCookie("ddAreaCookie");
ddAreaCookie.Value = DDLArea1.SelectedIndex.ToString();
ddAreaCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(ddAreaCookie);
}
public void DropDownCityIndexChange()
{
DDLArea1.Items.Clear();
DDLArea1.DataSource = null;
HttpCookie ddCityCookie = new HttpCookie("ddCityCookie");
ddCityCookie.Value = DDLCity1.SelectedIndex.ToString();
ddCityCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(ddCityCookie);
DataSet ds = new DataSet();
if (DDLCity1.SelectedItem.Text != "- All India -")
{
DataTable dt = new DataTable();
dt = objsql.GetTable("select area from tblCity where city='" + DDLCity1.SelectedItem.Text + "' and status=1 order by area");
if (dt.Rows[0]["area"].ToString() != null && dt.Rows[0]["area"].ToString() != "")
{
DDLArea1.DataSource = dt;
DDLArea1.DataTextField = "area";
DDLArea1.DataValueField = "area";
DDLArea1.DataBind();
}
}
DDLArea1.Items.Insert(0, new ListItem("- Anywhere -", "- Anywhere -"));
}
</code>
remove ClientIDMode="Static" Propery

Asp.Net dropdownlist showing blank after postback when page idle

I have 2 dropdownlists on my page. One for activity and one for sub activity. When the activity dropdownlist changes I retrieve the values for the sub activity dropdownlist . I am using a updatepanel for the second dropdownlist and the trigger is set to the first dropdownlist. This is working magicly until I leave the page to idle for a while 1-2min max. When I change the value for the activity dropdownlist(the trigger) it causes a full postback and the items for the second dropdownlist does not get populated.
Here is my code below.
Aspx
<div class="form-line">
<label>Activity</label>
<asp:DropDownList ID="ddlActivity" required="required" CssClass="chosen-select" runat="server" Width="200px" AppendDataBoundItems="true" OnSelectedIndexChanged="SelectedActivity_Changed" AutoPostBack="true" CausesValidation="false">
</asp:DropDownList>
</div>
<div class="form-line">
<label>Sub Activity</label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlActivity" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="ddlSubActivity" runat="server" Width="200px" required="required" CssClass="chosen-select" AppendDataBoundItems="true" CausesValidation="false">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Code behind
[ToolboxItemAttribute(false)]
public partial class MyEstimatesAdd : WebPart
{
static string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
ChronoLogDataContext dc = new ChronoLogDataContext(connStr);
// Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
// using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
// for production. Because the SecurityPermission attribute bypasses the security check for callers of
// your constructor, it's not recommended for production purposes.
// [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
public MyEstimatesAdd()
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Page.Request.QueryString["Issue_ID"] != "" && Page.Request.QueryString["Issue_ID"] != null)
{
Int64 issueid = Int64.Parse(Page.Request.QueryString["Issue_ID"]);
string sCurrentUserEmail;
SPUser cuser = SPControl.GetContextWeb(Context).CurrentUser;
sCurrentUserEmail = cuser.Email;
dc = new ChronoLogDataContext(connStr);
var resource = (from r in dc.RESOURCEs
where r.Email == sCurrentUserEmail
select r).FirstOrDefault();
ddlActivity.DataSource = (from a in dc.ACTIVITY_CATEGORies
select a).ToList();
ddlActivity.DataValueField = "Activity_Category_ID";
ddlActivity.DataTextField = "Description";
ddlActivity.DataBind();
ddlActivity.Items.Insert(0, new ListItem("", ""));
}
}
}
//RUN AGAIN PRIMARY SET
protected void btnAdd_Click(object sender, EventArgs e)
{
int hours;
if (!int.TryParse(txtHours.Text, out hours))
{
throw new SPException("Hours must be a numeric value");
}
string sCurrentUserEmail;
SPUser cuser = SPControl.GetContextWeb(Context).CurrentUser;
sCurrentUserEmail = cuser.Email;
dc = new ChronoLogDataContext(connStr);
var resource = (from r in dc.RESOURCEs
where r.Email == sCurrentUserEmail
select r).FirstOrDefault();
Int64 issueid = Int64.Parse(Page.Request.QueryString["Issue_ID"]);
decimal time = decimal.Parse(hours + "." + ddlMinutes.SelectedValue.ToString(), CultureInfo.InvariantCulture);
ESTIMATE estimate = new ESTIMATE { Activity_ID = int.Parse(ddlActivity.SelectedItem.Value), Date_Captured = DateTime.Now, Estimated_Time = time, Features = txtFeatures.Text, Issue_ID = issueid, Resource_ID = resource.Resource_ID, Sub_Activity_ID = int.Parse(ddlSubActivity.SelectedItem.Value) };
dc.ESTIMATEs.InsertOnSubmit(estimate);
dc.SubmitChanges();
Close_Save();
}
protected void Close_Save()
{
HttpContext context = HttpContext.Current;
if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
{
context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
context.Response.Flush();
context.Response.End();
}
}
protected void SelectedActivity_Changed(object sender, EventArgs e)
{
int activityid = int.Parse(ddlActivity.SelectedItem.Value);
dc = new ChronoLogDataContext(connStr);
var subactivities = (from s in dc.ACTIVITY_SUBCATEGORies
where s.Activity_Category_ID == activityid
select s).ToList();
ddlSubActivity.Items.Clear();
ddlSubActivity.DataSource = subactivities;
ddlSubActivity.DataValueField = "Activity_SubCategory_ID";
ddlSubActivity.DataTextField = "Description";
ddlSubActivity.DataBind();
ddlSubActivity.Items.Insert(0, new ListItem("", ""));
UpdatePanel1.Update();
}
}
Put both drop down lists within the same UpdatePanel or each in their own UpdatePanel, like this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlActivity" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<div class="form-line">
<label>Activity</label>
<asp:DropDownList ID="ddlActivity" required="required" CssClass="chosen-select" runat="server" Width="200px" AppendDataBoundItems="true" OnSelectedIndexChanged="SelectedActivity_Changed" AutoPostBack="true" CausesValidation="false">
</asp:DropDownList>
</div>
<div class="form-line">
<label>Sub Activity</label>
<asp:DropDownList ID="ddlSubActivity" runat="server" Width="200px" required="required" CssClass="chosen-select" AppendDataBoundItems="true" CausesValidation="false">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>

Categories

Resources