Partial page updating using update panel - html

I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?

Set AutoPostBack= true for the first ddl

U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}

Related

ASP.NET SQLDataSource SelectParameters default value not working

I wrote a simple ASP.NET form to manage a particular query on my (MySQL) db. Such query is handled by this stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `noleggio_conducenti`(IN _id_convenzionato INT(10))
BEGIN
IF _id_convenzionato IS NOT NULL THEN
SELECT * FROM
(
SELECT
*
FROM
noleggi AS H
WHERE
id_convenzionato = _id_convenzionato
UNION
SELECT
*
FROM
noleggi AS H
WHERE
id_convenzionato IN (SELECT
id_recipiente
FROM
sosautomotive.transizioni_point
WHERE
id_cedente = _id_convenzionato )
) H
WHERE (H.uscita IS NOT NULL) AND (H.rientro IS NOT NULL);
ELSE
SELECT
*
FROM
noleggi
WHERE (uscita IS NOT NULL) AND (rientro IS NOT NULL);
END IF;
END
As you can see the only parameter can be NULL ... my hope was to use this stored procedure to provide data to the following SQLDataSource object:
<asp:SqlDataSource
ID="_sdsConducenti"
runat="server"
ConnectionString="<%$ ConnectionStrings:sos_db %>"
ProviderName="<%$ ConnectionStrings:sos_db.ProviderName %>"
SelectCommandType="StoredProcedure"
SelectCommand="noleggio_conducenti">
<SelectParameters>
<asp:Parameter Name="_id_convenzionato" Type="Int32" DefaultValue="" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
That provides data to a GridView :
<asp:GridView
ID="_gvConducenti"
runat="server"
DataSourceID="_sdsConducenti"
OnSorting="_gvConducenti_Sorting"
OnPageIndexChanging="_gvConducenti_PageIndexChanging"
OnRowDataBound="_gvConducenti_RowDataBound"
AutoGenerateColumns="false"
EmptyDataText="Nessun conducente presente."
BorderStyle="None"
CellSpacing="0"
CellPadding="0"
ShowHeader="true"
ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
GridLines="Horizontal"
SelectedIndex="0"
Style="width: 100%;"
HorizontalAlign="Center">
<SelectedRowStyle CssClass="SelRow" />
<HeaderStyle CssClass="GridHeader" />
<AlternatingRowStyle BackColor="#F7F5E9" CssClass="AltRow" />
<PagerStyle HorizontalAlign="Center" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Pagina successiva"
PreviousPageText="Pagina precedente"
FirstPageText="Prima pagina"
LastPageText="Ultima pagina" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("idnoleggio")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Numero" SortExpression="numero">
<ItemTemplate>
<asp:LinkButton
runat="server"
CommandArgument='<%# Eval("idnoleggio")%>'
CommandName="Link"
OnCommand="Link_Command">
<%#Eval("numero_completo")%>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Conducente" DataField="conducente" />
<asp:BoundField HeaderText="Via" DataField="conducente_via" />
<asp:BoundField HeaderText="N° Civico" DataField="conducente_num_civico" />
<asp:BoundField HeaderText="CAP" DataField="conducente_cap" />
<asp:BoundField HeaderText="Città" DataField="conducente_residente_in" />
<asp:BoundField HeaderText="Prov." DataField="conducente_residente_in_provincia" />
<asp:BoundField HeaderText="Convenzionato" DataField="convenzionato" />
<asp:BoundField HeaderText="Uscita" DataField="uscita" DataFormatString="{0:dd/MM/yyyy HH:mm}" />
<asp:BoundField HeaderText="Rientro" DataField="rientro" DataFormatString="{0:dd/MM/yyyy HH:mm}" />
<asp:BoundField HeaderText="Tipologia noleggio" DataField="modalita_noleggio" />
</Columns>
</asp:GridView>
of course this form has other fields used to filter the query and those are handled by this couple of functions:
private void Ricerca()
{
if (!String.IsNullOrWhiteSpace(_txtConvenzionato.Text.Trim()))
{
int _nIdConvenzionato = CUtilita.RitornaIdConvenzionato(_txtConvenzionato.Text);
if (_nIdConvenzionato != -1)
_sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = _nIdConvenzionato.ToString();
else
_sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = null;
}
_sdsConducenti.FilterExpression = Filter();
}
private string Filter()
{
StringBuilder _sbFilter = new StringBuilder();
try
{
#region Data fine noleggio
if (!string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtDallaDataFineNoleggio = DateTime.Parse(_txtDallaDataFineNoleggio.Text.Trim());
DateTime _dtAllaDataFineNoleggio = DateTime.Parse(_txtAllaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("((uscita>='{0:yyyy-MM-dd}') AND (uscita<='{1:yyyy-MM-dd}'))", _dtDallaDataFineNoleggio, _dtAllaDataFineNoleggio);
}
else if (string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtAllaDataFineNoleggio = DateTime.Parse(_txtAllaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("(uscita<='{0:yyyy-MM-dd}')", _dtAllaDataFineNoleggio);
}
else if (!string.IsNullOrWhiteSpace(_txtDallaDataFineNoleggio.Text.Trim()) &&
string.IsNullOrWhiteSpace(_txtAllaDataFineNoleggio.Text.Trim()))
{
DateTime _dtDallaDataFineNoleggio = DateTime.Parse(_txtDallaDataFineNoleggio.Text.Trim());
_sbFilter.AppendFormat("(uscita>='{0:yyyy-MM-dd}')", _dtDallaDataFineNoleggio);
}
#endregion
}
catch (FormatException ex)
{
_lblStatus.Text = ex.Message;
_lblStatus.ForeColor = System.Drawing.Color.Red;
}
try
{
#region Data esportazione
if (!string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtDallaDataEstrazione = DateTime.Parse(_txtDallaDataEstrazione.Text.Trim());
DateTime _dtAllaDataEstrazione = DateTime.Parse(_txtAllaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("((data_esportazione_conducenti>='{0:yyyy-MM-dd}') AND (data_esportazione_conducenti<='{1:yyyy-MM-dd}'))", _dtDallaDataEstrazione, _dtAllaDataEstrazione);
}
else if (string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
!string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtAllaDataEstrazione = DateTime.Parse(_txtAllaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("(data_esportazione_conducenti<='{0:yyyy-MM-dd}')", _dtAllaDataEstrazione);
}
else if (!string.IsNullOrWhiteSpace(_txtDallaDataEstrazione.Text.Trim()) &&
string.IsNullOrWhiteSpace(_txtAllaDataEstrazione.Text.Trim()))
{
DateTime _dtDallaDataEstrazione = DateTime.Parse(_txtDallaDataEstrazione.Text.Trim());
_sbFilter.AppendFormat("(data_esportazione_conducenti>='{0:yyyy-MM-dd}')", _dtDallaDataEstrazione);
}
#endregion
}
catch (FormatException ex)
{
_lblStatus.Text = ex.Message;
_lblStatus.ForeColor = System.Drawing.Color.Red;
}
#region Tipo Noleggio
if (!string.IsNullOrWhiteSpace(_ddlTipoNoleggio.SelectedValue) && !_ddlTipoNoleggio.SelectedValue.Equals("TUTTI"))
{
if (_sbFilter.Length > 0)
_sbFilter.Append(" AND");
_sbFilter.Append("(modalita_noleggio = '" + _ddlTipoNoleggio.SelectedValue + "')");
}
#endregion
if (_sbFilter.Length == 0)
return null;
return _sbFilter.ToString();
}
I tested the stored procedure trough MySQL Workbench and I'm sure it works (both with a valid parameter and with NULL).
BUT when I try to use it within the form it works ONLY if the parameter value is provided and when then value is set to NULL (i.e. _sdsConducenti.SelectParameters["_id_convenzionato"].DefaultValue = null) the query did not provide any data (while it should retrieve a large number of records).
Where did I fail? How can I check if the NULL value is correctly set as the parameter value before calling the stored procedure?
Full code available here.
Try specifying below property in SQLDataSource definition -
CancelSelectOnNullParameter="false"
And it is described as
true if a data retrieval operation is canceled when a parameter
contained in the SelectParameters collection evaluated to null;
otherwise, false. The default is true
The similar problem is explained here -
Set SqlDataSource parameter to null
For more information refer here-

ASP.NET Button onklick resets label text

I am developing my first web application. I am trying to get the GPS location and save it for further processing. This is the code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CreatePlace.aspx.cs" Inherits="BeeMaster.CreatePlace" %>
<!DOCTYPE html>
<html style="background-image:url('images/background.png'); background-repeat:repeat-x">
<head runat="server">
<title>Create new Place</title>
<link href="CreatePlace.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#taComment {
height: 142px;
width: 339px;
}
</style>
</head>
<body>
<img src="Images/CNP.png" id="logo"/>
<br />
<br />
<br />
<br />
<br />
<br />
<div>
<p id="Comment" style="font-size: large">Click the button to get your position.</p>
<button onclick="getLocation()" style="font-size: xx-large; width: 380px; height: 50px;">
Get current location
</button>
<br />
<asp:Label ID="lblCoordinates" runat="server"></asp:Label><asp:Label ID="lblLat" runat="server"></asp:Label>,<asp:Label ID="lblLon" runat="server"></asp:Label>
<br />
<iframe
height="600"
style="border:0"
id="iFrame">
</iframe>
</div>
<form runat="server">
<br style="font-size: x-large" />
<br style="font-size: x-large" />
<asp:Label ID="lblName" runat="server" Text="Name:" Font-Size="X-Large"></asp:Label>
<br style="font-size: x-large" />
<asp:TextBox ID="tbName" runat="server" Font-Size="X-Large"></asp:TextBox>
<br style="font-size: x-large" />
<asp:Label ID="lblNameComment" runat="server" Text="It is recommended to give a name for the place." Font-Size="Medium"></asp:Label>
<br style="font-size: x-large" />
<br style="font-size: x-large" />
<asp:Label ID="lblComment" runat="server" Text="Comment:" Font-Size="X-Large"></asp:Label>
<br style="font-size: x-large" />
<textarea id="taComment" ></textarea>
<br style="font-size: x-large" />
<asp:Label ID="lblCommentComment" runat="server" Text="Comment specific for the physical place" Font-Size="Medium"></asp:Label>
<br style="font-size: x-large" />
<br style="font-size: x-large" />
<asp:Button ID="btSaveLocation" runat="server" Text="Save current location as new place" OnClick="btSaveLocation_Click" Font-Size="XX-Large" Height="50px" />
</form>
<script hidden="hidden">
var x = document.getElementById("Comment");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
document.getElementById("lblCoordinates").textContent += "Your location in Coordinates is: ";
document.getElementById("lblLat").innerHTML = position.coords.latitude;
document.getElementById("lblLon").innerHTML = position.coords.longitude;
document.getElementById("iFrame").src = "https://www.google.com/maps/embed/v1/place?key=<key>&q=" + latlon + "&maptype=satellite";
document.getElementById("iFrame").hidden = "";
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
When I click the first button, the two labels are getting filled out with the latitude and longitude as they are expected to.
When I click the button "Save current location as new place" it executes the following code in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace BeeMaster
{
public partial class CreatePlace : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btSaveLocation_Click(object sender, EventArgs e)
{
string lat = lblLat.Text;
string lon = lblLon.Text;
}
}
}
As you see, there is nothing in the Page_Load function, but still it seems to somehow reset the labels to their inital state because when I debug the application during run time and set a breakpoint at the beginning of the btSaveLocation_Click function then I see that the text of the two labels is blank already.
Does anybody know please what the problem is here?
Thanks
The content of a label is not part of a postback and thus will not be updated in the viewstate. Put your values in two hidden fields and use those to communicate with the server logic.
I found the solution. There were actually two problems:
The two labels that I was referring to in the codebehind file were not part of the form, they were in fact outside the form.
In the codebehind file I had to request their value in the Page_Load function and not in the function of the button.
This actually solved the problem.
Thanks everybody

Show/Hide Button depending on stored procedure return value

I'd like to get some help on an issue I'm having. I have a stored procedure that returns a dataset to fill a datagriview. One of the data grid's columns contains 2 manually set buttons, 'View' & 'Add'. These buttons open up a new popup window which displays extra information etc. I would like to be able to hide a 'View' button if 1 of the returned parameter's, POCount, count is equal to 0. i.e. there is nothing to view for that row. What is the best way to make this happen.
My stored procedure is
SELECT PM.ProjectCode,
PM.ProjectDesc,
PM.Active,
PM.Chargeable,
(SELECT COUNT(*) FROM POMaster PO WHERE PO.ProjectCode = PM.ProjectCode) AS POCount
FROM PROJECTMASTER PM
Front End Code
<asp:TemplateField HeaderText="P.O. Number" ItemStyle-Wrap="false" >
<ItemTemplate>
<asp:LinkButton ID="linkPONumber" runat="server" Text="View" CssClass="buttonStyle" OnClick="LinkPONumber_Click" CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>' ></asp:LinkButton>
<asp:LinkButton ID="linkAddPO" runat="server" Text="Add" CssClass="buttonStyle" OnClick="LinkAddPO_Click" CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code Behind
private void BindGrid()
{
DSProjectDetails = objProjectMasterBL.GetProjectDetails();
GvProject.DataSource = DSProjectDetails;
GvProject.DataBind();
}
public DataSet GetProjectDetails()
{
try
{
SqlProcedureName = "USP_GetProjectListWithPO";
SqlConnectionObject = DBConnection.InitializeConnection(SqlConnectionObject);
dsrepeater = SqlHelper.ExecuteDataset(SqlConnectionObject, CommandType.StoredProcedure, SqlProcedureName);
return dsrepeater;
}
catch (Exception ex)
{
log.Error("Exception in ProjectMasterBL.GetProjectDetails:", ex);
throw ex;
}
}
Apologies if I've sent the wrong sections of code, still residing in the noob ranks
You can use the Visible property of Link Button:-
<asp:LinkButton ID="linkAddPO" runat="server" Text="Add" CssClass="buttonStyle"
OnClick="LinkAddPO_Click" Visible='<%# Convert.ToInt32(Eval("POCount")) == 0 %>'
CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>'>
</asp:LinkButton>
Whenever your SP returns POCount as 0, you LinkButton will be hidden.

Validate dynamically created fields when one is changed

I have a program that dynamically creates various text boxes / drop down lists. I am trying to figure out how to validate these fields only when one is changed. Basically if someone entered a date in the text box then I need the program to validate that the drop down list was changed or vice versa. If there are no changes to both fields then it should not validate. Any help would be extremely appreciated. Here is the code:
<asp:TemplateField HeaderText="ValidatedDate" SortExpression="ValidatedDate">
<EditItemTemplate>
<asp:TextBox ID="txtValDate" Width="100px" MaxLength="10" runat="server" AutoPostBack="true"
Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}") %>'></asp:TextBox>
<asp:RegularExpressionValidator ValidationGroup="g1" ID="RegularExpressionValidator10"
runat="server" ControlToValidate="txtValDate" Display="None" ErrorMessage="Validated Date: ##/##/####"
ValidationExpression="\d{1,2}/\d{1,2}/\d{4}"></asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblValidatedDate" runat="server" Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductStatus" SortExpression="ProductStatusDescription">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource6" AutoPostBack="true"
DataTextField="StatusDescription" DataValueField="StatusID" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblProductStatus" runat="server" Text='<%# Bind("ProductStatusDescription")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
My apologies, the code can be a bit confusing without the correct context.
ebyrob, thank you for your help. I figured it out however and it works beautifully. Here is the code that fixed it all:
protected void AddError(string errorMessage)
{
cstValidate.IsValid = false;
cstValidate.ErrorMessage = errorMessage;
cstValidate.EnableClientScript = false;
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtValidatedDate = GridView2.Rows[e.RowIndex].FindControl("txtValDate") as TextBox;
DropDownList ddlStatusCompare = GridView2.Rows[e.RowIndex].FindControl("dropdownlist4") as DropDownList;
if (txtValidatedDate.Text == string.Empty && ddlStatusCompare.SelectedValue == "1")
{
AddError("Please enter a Validated Date");
e.Cancel = true;
}
else if (txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "0"
|| txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "99")
{
AddError("Please remove the Validated Date");
e.Cancel = true;
}
if (!e.Cancel)
Helpers.LogChanges(GridView2, e, _employeeID, "SaleProducts");
}

updatepanel does not trigger repeater itemcommand

I just want to trigger the LinkButton in a repeater which has a OnItemCommand. But the page do post back. Here is my code:
<asp:UpdatePanel ID="recommendedAdvertsUpPnl" runat="server">
<ContentTemplate>
<div class="tagList">
<asp:Label ID="lbListBookType" runat="server"></asp:Label>
<asp:Repeater ID="rpRecommendedAdvertFacultyList" runat="server" OnItemDataBound="rpRecommendedAdvertFacultyList_ItemDataBound" OnItemCommand="rpRecommendedAdvertFacultyList_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnAdvertFaculty" runat="server" CommandArgument='<%#Eval("facultyId") %>' CommandName="selectFaculty" CssClass="advertFacultySelection"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
</div>
<div class="RecommendedAdverts_List">
<asp:Repeater ID="rpRecommendedAdvertList" runat="server" OnItemDataBound="rpRecommendedAdvertList_ItemDataBound">
<HeaderTemplate>
<ul class="content_recommended">
</HeaderTemplate>
<ItemTemplate>
<%# Container.ItemIndex % 4 == 0 ? "<li><div class=advertContainer>": String.Empty%>
<div class="advertPanel">
<div class="rAdvPanel">
<div class="advertPic"><asp:Panel ID="pnlRecAdvertPic" runat="server"></asp:Panel></div>
<div class="advertInfoPanel">
<%#Eval("Book.Name")%> <br />
<%#Eval("Book.Authors")%><br />
<%#Eval("Price")%> TL<br />
</div>
</div>
</div>
<%# Container.ItemIndex % 4 == 3 ? "</div></li>": String.Empty%>
</ItemTemplate>
<FooterTemplate>
</div></li>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rpRecommendedAdvertFacultyList" EventName="ItemCommand" />
</Triggers>
</asp:UpdatePanel>
There is no problem except for triggering. Here is the my server side code:
protected void rpRecommendedAdvertFacultyList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
AdvertFacultyInfo item = (AdvertFacultyInfo)e.Item.DataItem;
LinkButton lbtnAdvertFaculty = (LinkButton)e.Item.FindControl("lbtnAdvertFaculty");
lbtnAdvertFaculty.Text = item.Faculty.name;
}
}
protected void rpRecommendedAdvertFacultyList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "selectFaculty":
List<AdvertFacultyInfo> advFacultyInfoList = EntitiyProvider.GetAdvertFacultyInfoListByFacultyId(Convert.ToInt32(e.CommandArgument));
List<Advert> selectedList = new List<Advert>();
foreach (AdvertFacultyInfo item in advFacultyInfoList)
{
Advert currentAdv = this.recommendedAdvertList.FirstOrDefault(i => i.id == item.advertId);
if ( currentAdv != null)
{
selectedList.Add(currentAdv);
}
}
rpRecommendedAdvertList.DataSource = selectedList;
rpRecommendedAdvertList.DataBind();
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script type='text/javascript'>$('.content_recommended').quickPager()</script>", false);
break;
default:
break;
}
}
I have also tried this code: But it gives error like lbtnAdvertFaculty could'nt find
<asp:AsyncPostBackTrigger ControlID="lbtnAdvertFaculty" EventName="Click" />
I have researched a lot of document written about this problem but I could not find useful examples and solution.
Best Regards.
try putting ClientIDMode="AutoID" to #page directive