Asp.Net dropdownlist showing blank after postback when page idle - c#

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>

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)
{
}

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

how add item from one listbox to another on web form

I have a two listboxes and a button. I need to add selected item from one listbox to another with click of button.
and here is the code of the button
protected void ASPxButton4_Click(object sender, EventArgs e)
{
if (listBoxSubeKiyaslama1.SelectedIndex > -1)
{
listBoxSubeKiyaslama2.Items.Add(listBoxSubeKiyaslama1.SelectedItem);
listBoxSubeKiyaslama2.Items.RemoveAt(listBoxSubeKiyaslama1.SelectedIndex);
listBoxSubeKiyaslama2.UnselectAll();
}
}
when I click the button, I see that listBoxSubeKiyaslama1.SelectedIndex is always "-1". because I think it postbacks and clears items from the first listbox. How can I fix this?
Can you try the below code:
if (listBoxSubeKiyaslama1.SelectedItem != null)
{
listBoxSubeKiyaslama2.Items.Add(listBoxSubeKiyaslama1.SelectedItem);
listBoxSubeKiyaslama2.Items.RemoveAt(listBoxSubeKiyaslama1.SelectedIndex);
listBoxSubeKiyaslama2.UnselectAll();
}
The controls will be not save the values on postbacks if EnableViewState = false. By default it is true. Please make sure you are not setting it to false.
I also suggest you to put your control in UpdatePanel to avoid full postback.
Like:
<asp:UpdatePanel ID="up1" runat="Server">
<ContentTemplate>
<asp:ListBox ID="listBoxSubeKiyaslama1" runat="server">
</asp:ListBox>
<asp:ListBox ID="listBoxSubeKiyaslama2" runat="server">
</asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
Try the following code:-
ASPX.CS
public string GetSelectedItems(ListBox control)
{
var items = new StringBuilder();
foreach (ListItem item in control.Items)
{
if (item.Selected)
items.Append(string.Format("{0},", item.Value));
}
return items.ToString().Trim().TrimEnd(',');
}
protected void btnMoveRight_Click(object sender, EventArgs e)
{
for (int i = lbCourses1.Items.Count - 1; i >= 0; i--)
{
if (lbCourses1.Items[i].Selected == true)
{
lbCourses2.Items.Add(lbCourses1.Items[i]);
ListItem li = lbCourses1.Items[i];
lbCourses1.Items.Remove(li);
}
}
}
protected void btnMoveLeft_Click(object sender, EventArgs e)
{
for (int i = lbCourses2.Items.Count - 1; i >= 0; i--)
{
if (lbCourses2.Items[i].Selected == true)
{
lbCourses1.Items.Add(lbCourses2.Items[i]);
ListItem li = lbCourses2.Items[i];
lbCourses2.Items.Remove(li);
}
}
}
var selectedValues = GetSelectedItems(lb2);
ASPX
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Label ID="lbl1" runat="server" Text="lbl1:"></asp:Label>
<asp:ListBox ID="lb1" runat="server" SelectionMode="Multiple"></asp:ListBox>
<asp:Button Runat="server" ID="btnMoveRight" Text=">>"
onclick="btnMoveRight_Click"></asp:Button>
<asp:Button Runat="server" ID="btnMoveLeft" Text="<<"
onclick="btnMoveLeft_Click"></asp:Button>
<asp:ListBox ID="lb2" runat="server" SelectionMode="Multiple"></asp:ListBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>

why the image isn't shown when it's in an UpdatePanel?

I have an image that placed in UpdatePanel. I set it's ImageUrl in button_click event.the image are in App_Data/imagesDirectory. Why isn't the image shown in the web page?
<asp:Panel ID="Panel1" runat="server" style="direction: ltr">
<asp:ListBox ID="photosListBox" runat="server" Rows="1"></asp:ListBox>
<asp:Button ID="selectButton" runat="server" Text="select"
onclick="selectButton_Click" />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<br />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Image ID="ph" runat="server" />
<br />
<br />
<asp:Button ID="submit" runat="server" onclick="submit_Click"
Text="submit" />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
im just set ImageUrl property in it that related the image control.however, the button code:
UpdatePanel2.Visible = true;
submit.Visible = true;
photosListBox.Visible = false;
selectButton.Visible = false;
Users sentUser = (Users)Session["user"];
Gallery sentGallery = (Gallery)Session["gallery"];
string selectedName = photosListBox.SelectedItem.ToString();
int selectedId = Convert.ToInt32(photosListBox.SelectedItem.Value);
ModelContainer ml = new ModelContainer();
Users u = ml.UsersSet.Where(t => t.Username == sentUser.Username).First();
Gallery g = u.Gallery.Where(t => t.Name == sentGallery.Name && t.Id == sentGallery.Id).First();
Photo p = g.Photo.Where(t => t.Name == selectedName && t.Id == selectedId).First();
ph.ImageUrl = MapPath(p.PhotoAdd);
nameTextBox.Text = p.Name;
descriptionTextBox.Text = p.Description;
uploadDateTimeLabel.Text = p.UploadDateTime.ToString();
i have also set ImageUrl attribute in PreRender event of the page.but it is'nt work:
protected void Page_PreRender(object sender, EventArgs e)
{
ph.ImageUrl = imageU;
}
imageU is a protected field of the page class
You must define ImageUrl in the PreRender event of your page
1 Find our data in event
2 Save data in variable of your page
3 Set attribute of Image on PreRender
Your photosListBox is not in the update panel so the selected value is not sent back to the server when submit_Click() is executing.

Updating the UI Thread from within a loop: ASP.NET Webforms

All,
I have an Update Panel control that contains a label control. I also have a Timer Control whose interval is set to 1 sec. The timer control is suppose to set the text of the label control every second with the value of a public property that changes after each iteration of the loop.
However the resulting functionality is that after the entire loop completes then the UI is updated. I'd like to know what would need to be done/coded to make sure the label control gets updated with the value of the _servername property after every iteration of the loop?
Heres my code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="tmr" runat="server" Interval="1000" ontick="tmr_Tick">
</asp:Timer>
<div>
<asp:UpdatePanel ID="udp1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tmr" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblInserts" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress runat="server" ID="udprg1" AssociatedUpdatePanelID="udp1"
DisplayAfter="10">
<ProgressTemplate>
<img src="media/ajaxloaderBlueLoading.gif" alt="ProgressImage" />
</ProgressTemplate>
</asp:UpdateProgress>
<div id="_asyncCallsMadeDiv"></div>
</div>
</form>
//CODE BEHIND
public string ServerName
{
get { return _serverName; }
set { _serverName = value;}
}
protected void tmr_Tick(object sender, EventArgs e)
{
lblInserts.Text = ServerName;
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//Loop through data
while((line = rdr.ReadLine()) != null)
{
string [] arrayline = line.Split(',');
ServerStatus s = new ServerStatus
{
ServerName = arrayline[0],
Purpose = arrayline[1],
Primary = arrayline[2],
Secondary = arrayline[3],
OS = arrayline[4],
MachineType = arrayline[5],
Comments = arrayline[6],
VMTools = arrayline[7],
TimeSettings = arrayline[8],
LastPatchDate = arrayline[9],
CARemoval = arrayline[10],
PLUpdate = arrayline[11],
DefaultGatewayChange = arrayline[12]
};
_serverName = arrayline[0];
}
The onTick property of your timer control is set to a method that doesn't exist. You can rename tmr_Tick method in your code behind to tmrUdp1_Tick or set the onTick property to tmr_Tick

Categories

Resources