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.
Related
I get a repeater with 3 radio button (grouped in 3 rows by GroupName property) and triggered (per each radio button). My problem is coming when I add a HiddenField to the repeater column and I want to reach this HiddenField through ItemCommand event.
The ItemCommand event is not raising...
(LinkButton click event is working as well)
(If a set CheckedChanged event of radio button they are working fine, but They are not helping because I need to reach the HiddenField)
This my code:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="lnkEliminarImagen" runat="server" OnClick="lnkEliminarImagen_Click" CausesValidation="false"><i class="fa fa-times" ></i></asp:LinkButton>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
<asp:HiddenField runat="server" ID="hdLogoId" Value='<%#Eval("id").ToString()%>' />
</span>
</ItemTemplate>
</asp:Repeater>
JS
for simulating GroupName behaviour. Avoiding to have more than one
radio button checked per row
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
I tried:
Surrounding the radio buttons by LinkButton (and use Click and Command event... None is raising...). It Didnt work.
Define the ItemCommand as usual (trick CauseValidation="false" as well). It didnt work. (1)
Setting the link between linkbutton and his function event programatically (as radio button). It didnt work.
ITEMCOMMAND CODE (1)
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound" OnItemCommand="repeaterImages_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkEliminarImagen" runat="server" OnClick="lnkEliminarImagen_Click" CausesValidation="false"><i class="fa fa-times" ></i></asp:LinkButton>
<span>
<asp:LinkButton runat="server" ID="lnkbtnbtn" OnCommand="lnkbtnbtn_Command" CommandArgument='<%#Eval("LOGO_ID").ToString()%>' CausesValidation="false" CommandName="prueba"></asp:LinkButton>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
<asp:HiddenField runat="server" ID="hdLogoId" Value='<%#Eval("id").ToString()%>' />
</span>
</ItemTemplate>
</asp:Repeater>
CS
protected void repeaterImages_ItemCommand(object source, RepeaterCommandEventArgs e)
{
HiddenField id = (HiddenField)e.Item.FindControl("hdLogoId");
string idlogo = id.Value;
switch (e.CommandName)
{
case ("prueba"):
string idid = e.CommandArgument.ToString();
break;
}
}
IDEA I AM LOOKING FOR
Associate each radiobutton to its image (through id) respectively.
When I, finally, submit I could do my stuff, knowing radiobutton (action I will do) and image (logo_id) specific
I have one page where I am making use of Update panel, Datalist and file upload. I am using visual studio 2010.
My fileupload is in data list and I am binding data list with dynamic table to repeat the file upload control.
Please see below layout image:
Here Main upper red highlighted border is showing the repeated data list and in that I have file upload control.
Now the data list is in Update Panel so the file upload was not working So in data list I have taken another update panel to make file upload work and that was also working properly but on clicking of green add button issue started arising as
A control with ID 'Upload' could not be found for the trigger in
UpdatePanel 'UpdatePanel1'.
Below is my html code and please remember I am just giving the part where issue is arises:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="Uppanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="dtcustomerregistration" runat="server" RepeatDirection="Vertical"
Width="100%" OnItemCommand="dtcustomerregistration_ItemCommand">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<label class="col-md-4 control-label" for="Pic">
Upload Image:</label>
<asp:FileUpload ID="Pic" runat="server" accept="image/gif, image/jpg, image/jpeg, image/png" />
<asp:Button ID="Upload" CommandArgument='<%#Eval("uniqueId") %>' CommandName="Edit"
runat="server" Text="Upload" OnClick="Upload_Click" />
<asp:Label ID="StatusLabel" runat="server" CssClass="requiredvalidate" Text=""></asp:Label>
<asp:HiddenField ID="hdimagename" runat="server" Value='<%#Eval("UploadImage") %>' />
<asp:Image ID="imgpicuploaded" runat="server" ImageUrl='<%#System.Configuration.ConfigurationManager.AppSettings["ShowImagetemppath"].ToString().Replace("~/","") +Eval("UploadImage").ToString() %>'
Height="50px" />
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Upload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:DataList>
<asp:ImageButton ID="imgplus" runat="server" ImageUrl="~/Image/Add.png" Height="50px" OnClick="imgplus_Click" />
</ContentTemplate>
</asp:UpdatePanel>
My code on imgplus click event is as below.
protected void imgplus_Click(object sender, ImageClickEventArgs e)
{
int n = (int)ViewState["n"];
n = n + 1;
BindData(n);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["data"] = null;
BindData(0);
}
}
public void BindData(int n)
{
DataTable dt = new DataTable();
dt.Columns.Add("uniqueId");
dt.Columns.Add("Invoice");
dt.Columns.Add("ReturnType");
dt.Columns.Add("ItemNumber");
dt.Columns.Add("ReturnQTY");
dt.Columns.Add("UnitofMeasure");
dt.Columns.Add("CreditPer");
dt.Columns.Add("ReasonCode");
dt.Columns.Add("InvoiceNumber");
dt.Columns.Add("Ordernumber");
dt.Columns.Add("Notes");
dt.Columns.Add("UploadImage");
if (ViewState["data"] == null)
{
dt = bindemptydata(dt, n);
}
else
{
foreach (DataListItem dli in dtcustomerregistration.Items)
{
HiddenField lblid = (HiddenField)dli.FindControl("lblid");
DropDownList RetCred = (DropDownList)dli.FindControl("RetCred");
DropDownList returntype = (DropDownList)dli.FindControl("returntype");
TextBox ItemNumber = (TextBox)dli.FindControl("ItemNumber");
TextBox ReturnQty = (TextBox)dli.FindControl("ReturnQty");
DropDownList Unit = (DropDownList)dli.FindControl("Unit");
TextBox Credit = (TextBox)dli.FindControl("Credit");
DropDownList ReasonCode = (DropDownList)dli.FindControl("ReasonCode");
TextBox Invoice = (TextBox)dli.FindControl("Invoice");
TextBox OrderNumber = (TextBox)dli.FindControl("OrderNumber");
TextBox Notes = (TextBox)dli.FindControl("Notes");
Image imgpicuploaded = (Image)dli.FindControl("imgpicuploaded");
HiddenField hdimagename = (HiddenField)dli.FindControl("hdimagename");
DataRow dr = dt.NewRow();
if (lblid.Value != "")
{
dr["uniqueId"] = lblid.Value;
}
else
{
dr["uniqueId"] = n;
}
dr["Invoice"] = RetCred.SelectedValue;
dr["ReturnType"] = returntype.SelectedValue;
dr["ItemNumber"] = ItemNumber.Text;
dr["ReturnQTY"] = ReturnQty.Text;
dr["UnitofMeasure"] = Unit.SelectedValue;
dr["CreditPer"] = Credit.Text;
dr["ReasonCode"] = ReasonCode.SelectedValue;
dr["InvoiceNumber"] = Invoice.Text;
dr["Ordernumber"] = OrderNumber.Text;
dr["Notes"] = Notes.Text;
dr["UploadImage"] = hdimagename.Value;
dt.Rows.Add(dr);
}
dt = bindemptydata(dt, n);
}
BindDatalist(dt);
ViewState["n"] = n;
}
public DataTable bindemptydata(DataTable dt, int n)
{
DataRow dr = dt.NewRow();
dr["uniqueId"] = n;
dr["Invoice"] = "Credit";
dr["ReturnType"] = "0";
dr["ItemNumber"] = "";
dr["ReturnQTY"] = "";
dr["UnitofMeasure"] = "Each";
dr["CreditPer"] = "100%";
dr["ReasonCode"] = "0";
dr["InvoiceNumber"] = "";
dr["Ordernumber"] = "";
dr["Notes"] = "";
dr["UploadImage"] = "";
dt.Rows.Add(dr);
return dt;
}
public void BindDatalist(DataTable dt)
{
dtcustomerregistration.DataSource = dt;
dtcustomerregistration.DataBind();// Here I am receiving error
ViewState["data"] = dt;
}
Here above I had given full code to create the dynamic data table and binding that with data list so that data list get repeated on click of imgplus button
But on click of button I am receiving error as :
Below is the error image.
How can I fix this?
On Click on Imgplus button I m receiving issue for upload button which exist in DataList.
And one more thing that if I normally click ImgPlus button without having use of Upload button click then it will repeat the DataList control without giving any issue but in case Once I made use of Upload click button exist in DataList and then after I click Imgplus button I receive error as:
A control with ID 'Upload' could not be found for the trigger in
UpdatePanel 'UpdatePanel1'.
Surround your button with another UpdatePanel upButton:
<asp:UpdatePanel ID="upButton" runat="server" UpdateMode="Conditional">
<asp:Button ID="Upload" CommandArgument='<%#Eval("uniqueId") %>' CommandName="Edit"
runat="server" Text="Upload" OnClick="Upload_Click" />
</ContentTemplate>
And then call your main UpdatePanel Uppanel.Update(); in your button click method Upload_Click.
Note: Remove UpdatePanel ID="UpdatePanel1".
You're error happens because of this code:
<Triggers>
<asp:PostBackTrigger ControlID="Upload" />
</Triggers>
You used PostBackTrigger while you are inside a nested pannel, while you shoud use
AsyncPostBackTrigger in this case as per this page.
So change that code segment to be:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Upload" />
</Triggers>
or set the UpdateMode of UpdatePanel1 to be "Always"
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
From a listview control, when checkboxes are checked and a button is clicked from outside the listview, I need to be able to delete the items that have been checked. Here's the listview:
EDIT
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
var notes = (from n in db.Notes
select n).OrderBy(n => n.FiscalYear).ThenBy(n => n.Period);
notesListView.DataSource = notes;
notesListView.DataBind();
}
<asp:ListView ID="notesListView" ItemPlaceholderID="itemPlaceholder" runat="server">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkNote" runat="server" />
<div><%# Eval("Period") %></div>
<div><%# Eval("FiscalYear") %></div>
<div><%# Eval("Account") %></div>
<div class="wrap"><%# Eval("Description") %></div>
</ItemTemplate>
<EmptyDataTemplate>
<div>No notes have been submitted.</div>
</EmptyDataTemplate>
</asp:ListView>
<br />
<asp:Button ID="deleteNotes" CssClass="deleteButton" Text="Delete Notes" runat="server" OnClick="deleteNotes_Click" />
Here's the code behind:
protected void deleteNotes_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in notesListView.Items)
{
// I know this is wrong, just not sure what to do
if (notesListView.SelectedIndex >= 0)
{
CheckBox ck = (CheckBox)item.FindControl("checkNote");
if (ck.Checked)
{
var index = item.DataItemIndex; // the item row selected by the checkbox
// db is the datacontext
db.Notes.DeleteOnSubmit(index);
db.SubmitChanges();
}
}
else
{
errorMessage.Text = "* Error: Nothing was deleted.";
}
}
}
You need to find the object before deleting it. To do so, I would add a hiddenfield to store NoteID like this:
<asp:HiddenField ID="hdnId" Value='<%#Eval("Id")%>' runat="server" />
<asp:CheckBox ID="checkNote" runat="server" />
... ... ...
And in my code I am finding the note by ID and deleting that note (You may use any other unique field instead of ID). My code may look like this:
... ... ...
int id = 0;
var hdnId = item.FindControl("hdnId") as HiddenField;
CheckBox ck = (CheckBox)item.FindControl("checkNote");
//I would check null for ck
if (ck != null && ck.Checked && hdnId != null && int.TryParse(hdnId.Value, out id)
{
// db is the datacontext
Note note = db.Notes.Single( c => c.Id== id );
db.Notes.DeleteOnSubmit(note );
db.SubmitChanges();
}
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>