I'm trying to get an aspx datagrid control to perform a post that results in a partial postback (asynchronous) rather than a full postback. I've added scriptmanager, an update panel, and a content template wrapper and yet it still refreshes the page when i select a data item and click add.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" ></asp:ScriptManager>
<asp:UpdatePanel ID="upPnlLookup" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:DataGrid ID="ObjectPropertiesDataGrid" CellPadding="5" CellSpacing="5" OnItemCommand="ObjectPropertiesDataGrid_ItemCommand" OnItemDataBound="ObjectPropertiesDataGrid_ItemDataBound" AutoGenerateColumns="False" CssClass="List" DataKeyField="id" runat="server">
<asp:TemplateColumn>
<ItemTemplate>
<asp:Panel ID="multiValuePanel" Visible="false" runat="server">
<table>
<tr>
<td valign="top">
<asp:Button ID="addButton" CssClass="button" CommandName="AddValue" Width="65px" Text="Add" runat="server"></asp:Button>
<asp:Button ID="addAllButton" CssClass="button" CommandName="AddAllValue" Width="85px" Text="Add All" runat="server"></asp:Button>
<br />
<asp:ListBox ID="listBoxValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
</td>
<td valign="top">
<asp:Button ID="removeButton" CssClass="button" Text="Remove" Width="65px" CommandName="RemoveValue" runat="server"></asp:Button>
<asp:Button ID="removeAllButton" CssClass="button" Text="Remove All" Width="85px" CommandName="RemoveAllValue" runat="server"></asp:Button>
<br />
<asp:ListBox ID="listBoxCurrentValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateColumn>
</asp:DataGrid>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="addButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="removeButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="addAllButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="removeAllButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind (snippets/relevant methods):
protected void Page_Load(object sender, EventArgs e)
{
SaveButton.Click += SaveButton_Click;
btnAddChild.Click += btnAddChild_Click;
btnAddChildTop.Click += btnAddChildTop_Click;
DeleteButton.Click += DeleteButton_Click;
CancelButton.Click += CancelButton_Click;
CopyButton.Click += CopyButton_Click;
NewButton.Click += NewButton_Click;
AddSiteButton.Click += AddSiteButton_Click;
RemoveSiteButton.Click += RemoveSiteButton_Click;
ActivateAll.Click += ActivateAll_Click;
DeactivateAll.Click += DeactivateAll_Click;
startDateCalender.SelectionChanged += startDateCalender_SelectionChanged;
endDateCalender.SelectionChanged += endDateCalender_SelectionChanged;
startDateCalender.Load += startDateCalender_Load;
endDateCalender.Load += endDateCalender_Load;
CacheButton.Click += CacheButton_Click;
if (IsPostBack)
return;
if (String.IsNullOrEmpty(Request["id"]))
{
Response.Redirect("default.aspx");
}
else
{
LoadData();
}
}
private void LoadData()
{
Properties = ContentProviderFactory.GetContentProvider().GetObjectTypeProperties(CurrentContentObject.Type, false);
uploadImage.DataSource = DataHelper.GetObjecTypeImageSizes(CurrentContentObject.Type);
uploadImage.Container = CurrentContentObject;
foreach (var property in from Property p in Properties
let objectProperty = CurrentContentObject.GetProperty(p.Id)
where objectProperty == null
select p)
{
CurrentContentObject.Items.Add(property);
}
ObjectPropertiesDataGrid.DataSource = Properties;
var children = ContentProviderFactory.GetContentProvider().GetContentObjectChildren(CurrentContentObject.Id);
dgObjectChildren.DataSource = children.Where(c => c.Active);
dgObjectInactiveChildren.DataSource = children.Where(c => !c.Active);
dgObjectParents.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectParents(CurrentContentObject);
ddlContentTypes.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
ddlContentTypesTop.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
SitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSitesAvailable(CurrentContentObject.Id);
SetSitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSites(CurrentContentObject.Id);
if (CurrentContentObject.Id == 0)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "/admin/Contentobjects/ObjectNotFound.aspx");
Response.End();
}
const string DATE_FORMAT = "MM/dd/yyyy";
if (CurrentContentObject.StartDate.ToString(DATE_FORMAT) != SqlDateTime.MinValue.Value.ToString(DATE_FORMAT))
{
startDateTextBox.Text = CurrentContentObject.StartDate.ToShortDateString();
}
if (CurrentContentObject.EndDate.ToString(DATE_FORMAT) != SqlDateTime.MaxValue.Value.ToString(DATE_FORMAT))
{
endDateTextBox.Text = CurrentContentObject.EndDate.Date.ToShortDateString();
}
DataBind();
//if its an orphan child/child, remove 'add child' button and pulldown
if (ddlContentTypes.Items.Count == 0)
{
btnAddChild.Visible = false;
ddlContentTypes.Visible = false;
}
if (ddlContentTypesTop.Items.Count == 0)
{
ddlContentTypesTop.Visible = false;
btnAddChildTop.Visible = false;
}
// Add delete confirmation javascript
DeleteButton.Attributes["onclick"] = "return confirm_object_delete();";
RenderTypeHeader();
RenderBreadcrumb();
if (CurrentContentObject.ParentId == 0)
{
UserInfo.AddToHistory(CurrentContentObject.Id, CurrentContentObject.Name);
}
else
{
UserInfo.AddToHistory(CurrentContentObject.Parent.Id, CurrentContentObject.Parent.Name);
}
startCalenderPanel.Visible = false;
endCalenderPanel.Visible = false;
}
protected void ObjectPropertiesDataGrid_ItemCommand(object sender, DataGridCommandEventArgs e)
{
var id = (int)ObjectPropertiesDataGrid.DataKeys[e.Item.ItemIndex];
switch (e.CommandName.ToLower())
{
case "clearimage":
{
// Delete the image (does not physically remove the image but will be replaced if new a new one updates)
var imageProperty = e.Item.FindControl("imageProperty") as Image;
var tbFileName = e.Item.FindControl("tbFileName") as TextBox;
tbFileName.Text = string.Empty;
imageProperty.ImageUrl = string.Empty;
break;
}
case "addvalue":
{
// Adds a property value to the list of properites
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
foreach(var item in listBoxValues.Items.Cast<ListItem>().Where(item => item.Selected))
{
// Add item to the set values
listBoxCurrentValues.Items.Add(item);
}
for (var i = listBoxValues.Items.Count - 1; i >= 0; i--)
{
if (listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
{
listBoxValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxCurrentValues);
break;
}
case "removevalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
for(var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
{
if(listBoxCurrentValues.Items[i].Selected)
{
listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
listBoxCurrentValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxValues);
break;
}
case "addallvalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
foreach(ListItem item in listBoxValues.Items)
{
// Add item to the set values
listBoxCurrentValues.Items.Add(item);
}
for(var i = listBoxValues.Items.Count - 1; i >= 0; i--)
{
if(listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
{
listBoxValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxCurrentValues);
break;
}
case "removeallvalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
for (var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
{
listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
listBoxCurrentValues.Items.RemoveAt(i);
}
SortListBox(listBoxValues);
break;
}
case "addalldatalistvalue":
{
var dataListValues = e.Item.FindControl("DataListValues") as DataList;
var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;
foreach (DataListItem item in dataListValues.Items)
{
ImageLink imageLink = ImageLinks[id][item.ItemIndex];
CurrentImageLinks[id].Add(imageLink);
}
for (var i = dataListValues.Items.Count - 1; i >= 0; i--)
{
if (CurrentImageLinks[id].Contains(ImageLinks[id][i]))
{
ImageLinks[id].RemoveAt(i);
}
}
dataListValues.DataSource = ImageLinks[id];
dataListCurrentValues.DataSource = CurrentImageLinks[id];
dataListValues.DataBind();
dataListCurrentValues.DataBind();
break;
}
case "removealldatalistvalue":
{
var dataListValues = e.Item.FindControl("DataListValues") as DataList;
var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;
for (var i = dataListCurrentValues.Items.Count - 1; i >= 0; i--)
{
ImageLinks[id].Add(CurrentImageLinks[id][i]);
CurrentImageLinks[id].RemoveAt(i);
}
dataListValues.DataSource = ImageLinks[id];
dataListCurrentValues.DataSource = CurrentImageLinks[id];
dataListValues.DataBind();
dataListCurrentValues.DataBind();
break;
}
}
}
I think you have a runtime error in Page_Load. for example if you have this wrong codes, your page will refresh instead of update:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Response.Redirect("WebForm1.aspx");
int.Parse("");
}
}
also try this :
Control me = FindControl(Request.Params.Get("__EVENTTARGET"));
if(FindControl(me!=addButton && me!=removeButton && me!=addAllButton && me!=removeAllButton)
{
if (IsPostBack)
return;
if (String.IsNullOrEmpty(Request["id"]))
{
Response.Redirect("default.aspx");
}
else
{
LoadData();
}
}
Related
I have two resource file Resource.resx and Resource.ar.resx
with the same keys but different english and arabic data
in the following code the text in the is working fine showing english and arabic data with the change in the dropdownlist while the text of the save button always shows English not arabic
</tr>
<tr>
<td><span><%=Resources.Resource.Citations%></span></td>
<td>
<input runat="server" id="taCitations" type="number" style="width: 600px;" /></td>
</tr>
</table>
<asp:Button ID="btnSave" runat="server" Text="<%$Resources:Resource, Save%>" CssClass="btn" OnClick="btnSave_Click" />
I have a dropdownlist in master page
<asp:DropDownList ID="ddlLang" runat="server" AutoPostBack="true">
<asp:ListItem Text="English" Value="en-US">
<asp:ListItem Text="Arabic" Value="ar-sa" />
</asp:DropDownList>
and my work to change language is in preRender of the master page
protected void Page_PreRender(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"].Contains("ddlLang"))
{
//Set the Language.
Language = Request.Form[Request.Form["__EVENTTARGET"]];
}
if (Language == "en-US")
{
Body.Attributes["dir"] = "ltr";
tdAppParticulars.Attributes["align"] = "right";
}
else
{
Body.Attributes["dir"] = "rtl";
tdAppParticulars.Attributes["align"] = "left";
}
Thread.CurrentThread.CurrentCulture = new CultureInfo(Language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Language);
List<ExtFormInstruction1> lefi = bal.ExtFormInstructionByType("External Reviewers");
formInstructions = new Hashtable();
formIDs = new Hashtable();
string currentItemURL = "";
foreach (ExtFormInstruction1 row in lefi)
{
string itemURL = row.Page;
formInstructions[row.Page] = Language == "ar-sa" ? "" : row.Instruction;
formIDs[row.Page] = row.FormID;
if (Language == "en-US")
{
lblPageTitle.Text = row.Title;
}
else if (Language == "ar-sa")
{
lblPageTitle.Text = bal.GetFormByPage(row.Page.Replace(".aspx", "Ar.aspx"))[0].Title;
}
}
MakeMenu(Language);
if (IsPostBack)
{
return;
}
lblApplicantEmail.Text = bal.GetApplicant(ApplicationID)[0].NameString;
lblEmployee.Text = erBAL.GetExtRevByID(ExtReviewerID)[0].Name;
/* printer friendly */
if (Utils.IsPrintMode())
{
tdLeftMenu.Visible = false;
lnkPrint.Visible = false;
}
lnkPrint.NavigateUrl = currentItemURL + "?print=1";
}
the Language is a property in master page
public string Language
{
set
{
Session["Language"] = value;
}
get
{
if (Session["Language"] != null)
{
return Session["Language"].ToString();
}
else
{
return "en-US";
}
}
}
I would rather do it like this:
<asp:Button ID="btnSave" runat="server" meta:resourceKey="SaveButton" CssClass="btn" OnClick="btnSave_Click" />
And in the Resource.resx file, the entries will be like
Name: SaveButton.Text
Value: Save
Name: SaveButton.Tooltip
Value: Click to Submit
Similarly in Resource.ar.resx file
Name: SaveButton.Text
Value: حفظ
Name: SaveButton.Tooltip
Value: انقر فوق لتقديم
I have read many articles on viewstate but I can't get my head around it.
Basically I want to have two listboxes with add and remove buttons and a Proceed button.
When the Proceed button is pressed, the previous is hidden and a textbox is presented for each item in the first list box with 2 drop down boxes to describe it + a textbox for each item in the second list box (also for the user to add a description).
I then want a Finalise Button to save all this information to a database.
So far I have the following code:
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
CreateDynamicControls();
Page.MaintainScrollPositionOnPostBack = true;
Build2.Visible = false;
Build3.Visible = false;
Build4.Visible = false;
Finish.Visible = false;
}
void AddC_Click(Object sender, EventArgs e)
{
criteria.Items.Add(addnewc.Text.ToString());
addnewc.Text = null;
}
void RemoveCriterion_Click(Object sender, EventArgs e)
{
for (int i = 0; i < criteria.Items.Count; i++)
{
if (criteria.Items[i].Selected)
{
criteria.Items.Remove(criteria.Items[i]);
i--;
}
}
}
void AddAlternative_Click(Object sender, EventArgs e)
{
alternatives.Items.Add(addnewa.Text.ToString());
addnewa.Text = null;
}
void RemoveAlternative_Click(Object sender, EventArgs e)
{
for (int i = 0; i < alternatives.Items.Count; i++)
{
if (alternatives.Items[i].Selected)
{
alternatives.Items.Remove(alternatives.Items[i]);
i--;
}
}
}
void Continue_Click(Object sender, EventArgs e)
{
Build1.Visible = false;
Build2.Visible = true;
Build3.Visible = true;
CreateDynamicControls();
Finish.Visible = true;
}
void CreateDynamicControls()
{
Build2.Controls.Clear();
Build3.Controls.Clear();
Build2.Controls.Add(new LiteralControl("<h3>Please define each criterion.</h3><p>By describing it and indicating if it is 1/2 and a/b.</p>"));
for (int i = 0; i < criteria.Items.Count; i++)
{
Build2.Controls.Add(new LiteralControl("<strong>" + criteria.Items[i].Text + "</strong> Description:<br />"));
TextBox criteriondesc = new TextBox();
Build2.Controls.Add(criteriondesc);
criteriondesc.ID = "c" + i.ToString();
criteriondesc.Rows = 3;
criteriondesc.Width = 850;
criteriondesc.TextMode = TextBoxMode.MultiLine;
Build2.Controls.Add(new LiteralControl("<br />"));
Build2.Controls.Add(new LiteralControl("Desc1: "));
DropDownList aim = new DropDownList();
aim.ID = i.ToString();
aim.Width = 250;
aim.Items.Add(new ListItem("1"));
aim.Items.Add(new ListItem("2"));
Build2.Controls.Add(aim);
Build2.Controls.Add(new LiteralControl(" Desc2: "));
DropDownList source = new DropDownList();
source.ID = i.ToString();
source.Width = 250;
source.Items.Add(new ListItem("a"));
source.Items.Add(new ListItem("b"));
Build2.Controls.Add(source);
Build2.Controls.Add(new LiteralControl("<br /><br />"));
}
Build3.Controls.Add(new LiteralControl("<h3>Please define each alternative.</h3><p>Please describe each alternaitve in detail.</p>"));
for (int i = 0; i < alternatives.Items.Count; i++)
{
Build3.Controls.Add(new LiteralControl("<strong>" + alternatives.Items[i].Text + "</strong> Description:<br />"));
TextBox altdesc = new TextBox();
altdesc.ID = "a" + i.ToString();
altdesc.Rows = 3;
altdesc.Width = 850;
altdesc.TextMode = TextBoxMode.MultiLine;
Build3.Controls.Add(altdesc);
Build3.Controls.Add(new LiteralControl("<br />"));
}
Build3.Controls.Add(new LiteralControl("<br /><h3>Review dates.</h3><p>Please select a date for a meeting.</p>"));
OboutInc.Calendar2.Calendar selectdates = new OboutInc.Calendar2.Calendar();
Build3.Controls.Add(selectdates);
}
void Finish_Click(Object sender, EventArgs e)
{
Build4.Visible = true;
foreach (var control in Build2.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
foreach (var control in Build3.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
}
</script>
<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
<asp:Panel ID="Build1" runat="server">
<h3>What is your aim?</h3>
<p>
<asp:TextBox ID="goal" runat="server" Width="850px"></asp:TextBox>
</p>
<h3>What are the criteria of your decision?</h3>
<p>
<asp:ListBox ID="criteria" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveCriterion" runat="server" Text="Remove" OnClick="RemoveCriterion_Click" />
<asp:TextBox ID="addnewc" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddC" runat="server" Text="Add" OnClick="AddC_Click" />
</p>
</p>
<h3>What are the alternatives of your decision?</h3>
<p>
<asp:ListBox ID="alternatives" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveAlternative" runat="server" Text="Remove" OnClick="RemoveAlternative_Click" />
<asp:TextBox ID="addnewa" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddAlternative" runat="server" Text="Add" OnClick="AddAlternative_Click" />
</p>
<p align="right"><asp:Button ID="continue" runat="server" Text="Continue" OnClick="Continue_Click" /></p>
</asp:Panel>
<asp:Panel ID="Build2" runat="server">
</asp:Panel>
<asp:Panel ID="Build3" runat="server">
</asp:Panel>
<asp:Panel ID="Build4" runat="server">
</asp:Panel>
<p align="right"><asp:Button ID="Finish" runat="server" Text="Finish" OnClick="Finish_Click" /></p>
</asp:Content>
As you can see, at the minute I am just trying to output the user's text from the dynamically created textbox fields.
However, I am getting the error
Failed to load viewstate. The control tree into which viewstate is
being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial
request.
at: Line 169: Build3.Controls.Add(altdesc);
Does anyone know how to fix this problem with the viewstate?
I am very new to ASP.NET, my background is mainly in WinForms.
Thank you for any help and advice!!
You are creating your controls too late. You should create them during the Init events of the page, and not Page Load. I suggest You read abit about page life cycle
I think the best way to do it, it would be :
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
CreateDynamicControls();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
CreateDynamicControls();<br/>
}
Small sample:
http://class10e.com/Microsoft/which-method-should-you-add-to-the-web-page
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
On my Webpage I try to add User Control elements dependant on checked boxes in a tree view. Therefore I create a table that contains the tree view and a panel in which these elements should be loaded. The structure is like this:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script language="javascript" type="text/javascript">
function doCheckBoxPostBack(e) {
var event = window.event ? window.event.srcElement : e.target;
if (event.tagName == "INPUT" && event.type == "checkbox")
__doPostBack("", "");
}
</script>
<form id="form1" runat="server">
<h1>Status</h1>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td colspan="2" align="left" style="font-size:large">
Auswahl der anzuzeigenden Areas
</td>
</tr>
<tr>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<td valign="top">
<asp:TreeView ID="tvAreaSelect" runat="server"
onclick="doCheckBoxPostBack(event)" ShowCheckBoxes="All"
ontreenodecheckchanged="tvAreaSelect_TreeNodeCheckChanged">
<DataBindings>
<asp:TreeNodeBinding DataMember="System.Data.DataRowView" TextField="Text" ValueField="ID" />
</DataBindings>
</asp:TreeView>
</td>
<td>
<div style="overflow:auto; height:740px;">
<asp:Panel ID="panelContent" runat="server">
</asp:Panel>
</div>
</td>
</ContentTemplate>
</asp:UpdatePanel>
</tr>
</table>
</div>
</form>
</asp:Content>
In the code behind I load or unload my User Controls whenever one of the checkboxes changes its Checked value. This works just like it should, but when I press any button in one of the controls all of them disappear. Do I have to keep them in the cache or are there any other things to attend?
Here is a part of my code. I hope it makes clear what I'm doing.
protected void Page_Load(object sender, EventArgs e)
{
if (AreaIds.currList == null)
AreaIds.currList = new List<int>();
if (!this.Page.IsPostBack)
{
DataSet dsAreaGroups = dbStat.getDataSetAreaGroups();
DataSet dsAreasNotInAreaGroups = dbStat.getDataSetAreasNotInAreaGroups();
DataSet dsAreasInGroups = dbStat.getDataSetAreaGroupsWithAreas();
DataSet dsTree = new DataSet();
dsTree.Tables.Add("Table");
dsTree.Tables[0].Columns.Add("ID", typeof(string));
dsTree.Tables[0].Columns.Add("ParentID", typeof(string));
dsTree.Tables[0].Columns.Add("Text", typeof(string));
DataTableReader dtr = dsAreaGroups.CreateDataReader();
while (dtr.Read())
{
DataRow row = dsTree.Tables[0].NewRow();
object[] vals = new object[dtr.FieldCount];
dtr.GetValues(vals);
int inAreaGroupID = (int)vals.ElementAt(0);
string stName = (string)vals.ElementAt(1);
row["ID"] = inAreaGroupID;
row["Text"] = stName;
dsTree.Tables[0].Rows.Add(row);
}
dtr = dsAreasInGroups.CreateDataReader();
while (dtr.Read())
{
DataRow row = dsTree.Tables[0].NewRow();
object[] vals = new object[dtr.FieldCount];
dtr.GetValues(vals);
int inAreaID = (int)vals.ElementAt(0);
int inAreaGroupID = (int)vals.ElementAt(1);
string stName = (string)vals.ElementAt(2);
string stCombo = inAreaGroupID + "-" + inAreaID;
row["ID"] = stCombo;
row["ParentID"] = inAreaGroupID;
row["Text"] = stName;
dsTree.Tables[0].Rows.Add(row);
}
dtr = dsAreasNotInAreaGroups.CreateDataReader();
while (dtr.Read())
{
DataRow row = dsTree.Tables[0].NewRow();
object[] vals = new object[dtr.FieldCount];
dtr.GetValues(vals);
int inAreaID = (int)vals.ElementAt(0);
string stName = (string)vals.ElementAt(1);
row["ID"] = "0-" + inAreaID;
row["Text"] = stName;
dsTree.Tables[0].Rows.Add(row);
}
tvAreaSelect.SetDataSourceFromDataSet(dsTree, "ID", "ParentID");
tvAreaSelect.DataBind();
}
}
public void includeAreas(List<int> areaId)
{
int[] array = areaId.ToArray();
for (int i = 0; i < array.Length; i++)
{
Control ctrl = LoadControl("StatusArea.ascx", areaId[i]);
this.panelContent.Controls.Add(ctrl);
}
}
/// <summary>
/// Bereitstellung eines UserControl aus einer ascx-Datei
/// </summary>
/// <param name="UserControlPath">Das UserControl ascx-Datei</param>
/// <param name="constructorParameters">Parameter im Konstruktor der ascx.cs-Datei</param>
/// <returns>UserControl mit den entsprechenden Parametern</returns>
private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
{
List<Type> constParamTypes = new List<Type>();
foreach (object constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}
UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;
// Find the relevant constructor
System.Reflection.ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());
//And then call the relevant constructor
if (constructor == null)
{
throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
}
else
{
constructor.Invoke(ctl, constructorParameters);
}
// Finally return the fully initialized UC
return ctl;
}
protected void tvAreaSelect_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
TreeNode selNode = (TreeNode)e.Node;
TreeNode parentNode = selNode.Parent;
if (selNode.Checked && selNode.ChildNodes.Count == 0)
{
string stTest = selNode.Value.Substring(selNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
if (!AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Add(inAreaID);
}
if (!selNode.Checked && selNode.ChildNodes.Count == 0)
{
string stTest = selNode.Value.Substring(selNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
if (AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Remove(inAreaID);
}
foreach (TreeNode childNode in selNode.ChildNodes)
{
if (selNode.Checked)
{
string stTest = childNode.Value.Substring(childNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
childNode.Checked = true;
if (!AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Add(inAreaID);
}
else
{
string stTest = childNode.Value.Substring(childNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
childNode.Checked = false;
if (AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Remove(inAreaID);
}
}
includeAreas(AreaIds.currList);
}
Thanks in advance
I do believe your problem resides on the fact that unfortunately you need to reload your dynamic controls on each and every postback.
One solution is to keep a in-session list of 'loaded' controls, and recreate them at Page_Init.
I'm new to asp.net and have some clue but not sure how to do this so any help would be great thank you.
I have a Datalist with paging how do the update the datalist from user input via Dropdown list which will bind my datalist and paging?
My private properties
private int CurrentPage
{
get
{
object objPage = ViewState["_CurrentPage"];
int _CurrentPage = 0;
if (objPage == null)
{
_CurrentPage = 0;
}
else
{
_CurrentPage = (int)objPage;
}
return _CurrentPage;
}
set { ViewState["_CurrentPage"] = value; }
}
private int fistIndex
{
get
{
int _FirstIndex = 0;
if (ViewState["_FirstIndex"] == null)
{
_FirstIndex = 0;
}
else
{
_FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
}
return _FirstIndex;
}
set { ViewState["_FirstIndex"] = value; }
}
private int lastIndex
{
get
{
int _LastIndex = 0;
if (ViewState["_LastIndex"] == null)
{
_LastIndex = 0;
}
else
{
_LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
}
return _LastIndex;
}
set { ViewState["_LastIndex"] = value; }
}
Private methods
private void BindItemsList()
{
DataTable dataTable = dm.GetDataTable().Tables["product"];// middle tier which pulls data from a database
_PageDataSource.DataSource = dataTable.DefaultView;
_PageDataSource.AllowPaging = true;
_PageDataSource.PageSize = 1;
_PageDataSource.CurrentPageIndex = CurrentPage;
ViewState["TotalPages"] = _PageDataSource.PageCount;
this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;
this.dlPhones.DataSource = _PageDataSource;
this.dlPhones.DataBind();
this.doPaging();
}
/// <summary>
/// Binding Paging List
/// </summary>
private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");
fistIndex = CurrentPage - 5;
if (CurrentPage > 5)
{
lastIndex = CurrentPage + 5;
}
else
{
lastIndex = 10;
}
if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
{
lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
fistIndex = lastIndex - 10;
}
if (fistIndex < 0)
{
fistIndex = 0;
}
for (int i = fistIndex; i < lastIndex; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}
this.dlPaging.DataSource = dt;
this.dlPaging.DataBind();
}
Code behind page code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindItemsList();
}
}//end of page load
protected void lbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
this.BindItemsList();
}
protected void lbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
this.BindItemsList();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Paging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
this.BindItemsList();
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Style.Add("fone-size", "14px");
lnkbtnPage.Font.Bold = true;
}
}
protected void lbtnLast_Click(object sender, EventArgs e)
{
CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
this.BindItemsList();
}
protected void lbtnFirst_Click(object sender, EventArgs e)
{
CurrentPage = 0;
this.BindItemsList();
}
asp.net front page
<asp:Label ID="lblSearch" runat="server" Text="Search By Phone"></asp:Label>
<asp:DropDownList ID="ddlCat" runat="server">
<asp:ListItem>Nokia</asp:ListItem>
<asp:ListItem>Samsung</asp:ListItem>
<asp:ListItem>Motorola</asp:ListItem>
<asp:ListItem>Sony</asp:ListItem>
<asp:ListItem>Ericsson</asp:ListItem>
<asp:ListItem>Sony</asp:ListItem>
<asp:ListItem>LG</asp:ListItem>
<asp:ListItem>Apple</asp:ListItem>
<asp:ListItem>HTC</asp:ListItem>
<asp:ListItem>BlackBerry</asp:ListItem>
<asp:ListItem>HP</asp:ListItem>
<asp:ListItem>Huawei</asp:ListItem>
<asp:ListItem>Acer</asp:ListItem>
<asp:ListItem>Asus</asp:ListItem>
<asp:ListItem>Dell</asp:ListItem>
<asp:ListItem>Alcatel</asp:ListItem>
<asp:ListItem>Vodafone</asp:ListItem>
<asp:ListItem>T-Mobile</asp:ListItem>
<asp:ListItem>Toshiba</asp:ListItem>
<asp:ListItem>Gigabyte</asp:ListItem>
<asp:ListItem>Pantech</asp:ListItem>
<asp:ListItem>ZTE</asp:ListItem>
<asp:ListItem>Micromax</asp:ListItem>
<asp:ListItem>BLU</asp:ListItem>
<asp:ListItem>Spice</asp:ListItem>
<asp:ListItem>Icemobile</asp:ListItem>
<asp:ListItem>verykool</asp:ListItem>
<asp:ListItem>Vertu</asp:ListItem>
<asp:ListItem>Celkon</asp:ListItem>
<asp:ListItem>NIU</asp:ListItem>
<asp:ListItem>Yezz</asp:ListItem>
<asp:ListItem>Parla</asp:ListItem>
<asp:ListItem>Plum</asp:ListItem>
<asp:ListItem>Sim Card</asp:ListItem>
</asp:DropDownList>
<asp:DataList ID="dlPhones" runat="server" DataKeyField="PID" RepeatDirection="Horizontal" RepeatColumns="1" CellPadding="10" CellSpacing="10" >
<ItemTemplate>
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />
<br />Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# "$" + Eval("Price") %>' />
<br />
<asp:Image ID="Image1" runat="server" CssClass="ImageStyles" ImageUrl='<%# "GetImage.ashx?Id=" + Eval("PID") %>' BackColor="White" BorderStyle="Ridge" BorderColor="WhiteSmoke" />
<br />
</ItemTemplate>
</asp:DataList>
<table cellpadding="0" border="0">
<tr>
<td align="right">
<asp:LinkButton ID="lbtnFirst" runat="server" CausesValidation="false" OnClick="lbtnFirst_Click"><img src="images/First.png" height="50px" width="100px" onmouseover="this.src='images/FirstMouseOver.png';" onmouseout="this.src='images/First.png';" /></asp:LinkButton>
</td>
<td align="right">
<asp:LinkButton ID="lbtnPrevious" runat="server" CausesValidation="false" OnClick="lbtnPrevious_Click"><img src="images/Previouse.png" onmouseover="this.src='images/PreviouseMouseOver.png';" onmouseout="this.src='images/Previouse.png';" /></asp:LinkButton> </td>
<td align="center" valign="middle">
<asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand"
OnItemDataBound="dlPaging_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPaging" Font-Size="X-Large" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
CommandName="Paging" Text='<%# Eval("PageText") %>'></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</td>
<td align="left">
<asp:LinkButton ID="lbtnNext" runat="server" CausesValidation="false"
OnClick="lbtnNext_Click"><img src="images/Next.png" onmouseover="this.src='images/NextMouseOver.png';" onmouseout="this.src='images/Next.png';" /></asp:LinkButton></td>
<td align="left">
<asp:LinkButton ID="lbtnLast" runat="server" CausesValidation="false" OnClick="lbtnLast_Click"><img src="images/Last.png" onmouseover="this.src='images/LastMouseOver.png';" onmouseout="this.src='images/Last.png';" /></asp:LinkButton></td>
</tr>
<tr>
<td colspan="5" align="center" style="height: 30px" valign="middle">
<asp:Label ID="lblPageInfo" runat="server"></asp:Label></td>
</tr>
</table>
i figured it out myself just what to post the solution just in case any one has the same problem.
I'm not sure if this the best way to do it, so please forgive me.
1) Create a Session["search"] = "First";
2) Create a method for dropdownlist onselectindexchange
<asp:DropDownList ID="ddlCat" runat="server" AutoPostBack="true" OnSelectedIndexChanged="itemSelected">
Code behind method
protected void itemSelected(object sender, EventArgs e)
{
Session["search"] = "Second";
RebindItemList();
}
3) rebind method
private void RebindItemList()
{
DataTable dataTable = dm.GetSpecifProduct(ddlCat.SelectedItem.Text).Tables["product"];// middle tier method with returns a Dataset or DataTable up to you.
_PageDataSource.DataSource = dataTable.DefaultView;
_PageDataSource.AllowPaging = true;
_PageDataSource.PageSize = 1;
_PageDataSource.CurrentPageIndex = CurrentPage;
ViewState["TotalPages"] = _PageDataSource.PageCount;
this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;
this.dlPhones.DataSource = _PageDataSource;
this.dlPhones.DataBind();
this.doPaging();
}
4) logic statement for your paging buttons
protected void lbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
string searchCat = (string) Session["search"];
if (searchCat == "First")
{
this.BindItemsList();
}
if (searchCat == "Second")
{
this.RebindItemList();
}
}
protected void lbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
string searchCat = (string)Session["search"];
if (searchCat == "First")
{
this.BindItemsList();
}
if (searchCat == "Second")
{
this.RebindItemList();
}
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Paging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
string searchCat = (string)Session["search"];
if (searchCat == "First")
{
this.BindItemsList();
}
if (searchCat == "Second")
{
this.RebindItemList();
}
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Style.Add("fone-size", "14px");
lnkbtnPage.Font.Bold = true;
}
}
protected void lbtnLast_Click(object sender, EventArgs e)
{
CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
string searchCat = (string)Session["search"];
if (searchCat == "First")
{
this.BindItemsList();
}
if (searchCat == "Second")
{
this.RebindItemList();
}
}
protected void lbtnFirst_Click(object sender, EventArgs e)
{
CurrentPage = 0;
string searchCat = (string)Session["search"];
if (searchCat == "First")
{
this.BindItemsList();
}
if (searchCat == "Second")
{
this.RebindItemList();
}
}
I have problem on page bellow, in gdvCar_DataBound I add three buttons, when I click on any of them, page go to postback but doesn't enter in gdvCar_RowCommand and then that buttons ( and images that I also add in gdvCar_DataBound) disaper. Grid is then full like gdvCar_DataBound isn't execute. My question is why it doesn't enter at gdvCar_RowCommand ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HMS.library;
using System.Data.SqlClient;
namespace HMS
{
public partial class Cars : System.Web.UI.Page
{
#region fields
private const Int16 PageId = 1;
private String connectionString = "Server=localhost;Database=hms_test;Trusted_Connection=True;";
String[] filters = null;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillProducer();
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
RestoreFilters();
FillGrid();
}
}
#region events
protected void ddlProducer_Changed(object sender, EventArgs e)
{
if (ddlProducer.SelectedValue != "0")
{
ddlModel.Enabled = true;
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
}
else
{
ddlModel.SelectedValue = "0";
ddlModel.Enabled = false;
}
upSearch.Update();
}
protected void gdvCar_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Reserve":
{
pnlReserve.Visible = true;
break;
}
case "Phone":
{
break;
}
case "Email":
{
break;
}
}
}
protected void gdvCar_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String id = e.Row.Cells[0].Text;
Image img = new Image();
img.ID = "img_one" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[7].Text;
e.Row.Cells[7].Controls.Add(img);
img = new Image();
img.ID = "img_two" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[8].Text;
e.Row.Cells[8].Controls.Add(img);
img = new Image();
img.ID = "img_three" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[9].Text;
e.Row.Cells[9].Controls.Add(img);
ImageButton imbReserve = new ImageButton();
imbReserve.ID = "res" + id;
imbReserve.Enabled = true;
imbReserve.Width = 48; imbReserve.Height = 48;
imbReserve.ToolTip = "Reserve"; imbReserve.AlternateText = "Reserve";
imbReserve.ImageUrl = "images/icons/key.gif";
imbReserve.CommandName = "Reserve";
imbReserve.CommandArgument = id;
e.Row.Cells[10].Controls.Add(imbReserve);
ImageButton imbPhone = new ImageButton();
imbPhone.ID = "phone" + id;
imbPhone.Enabled = true;
imbPhone.Width = 48; imbPhone.Height = 48;
imbPhone.ToolTip = "Reserve by phone"; imbPhone.AlternateText = "Phone";
imbPhone.ImageUrl = "images/icons/phone.jpg";
imbPhone.CommandName = "Phone";
imbPhone.CommandArgument = id;
e.Row.Cells[11].Controls.Add(imbPhone);
ImageButton imbEmail = new ImageButton();
imbEmail.ID = "email" + id;
imbEmail.Enabled = true;
imbEmail.Width = 48; imbEmail.Height = 48;
imbEmail.ToolTip = "Reserve by email"; imbEmail.AlternateText = "Email";
imbEmail.ImageUrl = "images/icons/email.jpg";
imbEmail.CommandName = "Email";
imbEmail.CommandArgument = id;
e.Row.Cells[12].Controls.Add(imbEmail);
}
}
protected void imbSearch_Click(object sender, ImageClickEventArgs e)
{
StoreFilters();
FillGrid();
}
#endregion
#region functions
private void FillProducer()
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.producer_cars
orderby o.name
select new
{
o.id,
o.name
};
foreach (var temp in source)
ddlProducer.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlProducer.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillModel(int producer_id)
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.model_cars
from p in hms.producer_cars
where o.producer_car_id == producer_id && p.id == producer_id
orderby o.name
select new
{
o.id,
o.name
};
ddlModel.Items.Clear();
foreach (var temp in source)
ddlModel.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlModel.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillGrid()
{
SqlConnection conn = new SqlConnection(connectionString);
String command = #"SELECT car.id AS id, car.price as price, car.weight as weight,
car.year as year, producer_car.name as producer, model_car.name as model, car.number_seats as number_seats, car.photo_one as photo_one,car.photo_two as photo_two,car.photo_three as photo_three, '' as reserver,'' as phone,'' as email
FROM car INNER JOIN model_car on car.model_car_id=model_car.id
INNER JOIN producer_car on model_car.producer_car_id=producer_car.id";
if(filters!=null){
String[] search=new String[5];
search[0]=filters[0]!="0"?"producer_car.id="+filters[0]:"";
search[1]= filters[1] != "0" ? "model_car.id=" + filters[1] : "";
search[2]=filters[2]!=""?"car.color LIKE \'"+filters[2]+"\'":"";
search[3]=filters[3]!=""?"car.price<"+filters[3]:"";
search[4] = filters[4] != "" ? "car.number_seats=" + filters[4] : "";
var a=from f in search
where f!=""
select f;
String filterAddition="";
if(a.Count()>0){
filterAddition=" WHERE ";
foreach ( var b in a){
filterAddition+=" "+b+" AND";
}
filterAddition=filterAddition.EndsWith("AND")?filterAddition.Substring(0,filterAddition.Length-3):filterAddition;
}
command+=filterAddition;
}
SqlCommand comm = new SqlCommand(command, conn);
SqlDataReader r = null;
try
{
comm.Connection.Open();
r =comm.ExecuteReader();
gdvCar.DataSource = r;
gdvCar.DataBind();
r.Close();
}
catch (Exception exc)
{
throw (exc);
}
finally
{
conn.Close();
}
}
private void StoreFilters()
{
filters = new String[5];
filters[0] = ddlProducer.SelectedValue;
filters[1] = ddlModel.SelectedValue;
filters[2] = ddlColor.SelectedValue;
filters[3] = txtStartPrice.Text;
filters[4] = ddlNumber.SelectedValue;
Session["1"] = filters;
}
private void RestoreFilters()
{
if (Session["1"] != null)
{
filters = (String[])Session["1"];
ddlProducer.SelectedValue = filters[0];
ddlProducer_Changed(null, null);
ddlModel.SelectedValue = filters[1];
ddlColor.SelectedValue = filters[2];
txtStartPrice.Text = filters[3];
ddlNumber.SelectedValue = filters[4];
}
}
private void ReserveCar(String FirstName, String LastName, DateTime Start, DateTime End, String Visa, Int16 CarId)
{
hmsDataContext hms = new hmsDataContext();
var a = from c in hms.cars
from rc in hms.rented_cars
where c.id == rc.id_car && c.id == CarId
select new
{
start = rc.start,
end = rc.end
};
Boolean free = false;
if (a.Count() == 0)
{
free = true;
}
else if (a.Count() == 1)
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
}
else
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
else if(!free)
{
int n = a.Count();
for (int i = 0; (i < n - 1) && (!free); i++)
{
if (a.ElementAt(i).end < Start && a.ElementAt(i + 1).start > End)
free = true;
i++;
}
if (!free)
{
if (a.ElementAt(n - 1).end < Start)
free = true;
}
}
}
if (free)
{
//insert
}
else
{
//label-nije slobodno za taj termin
}
}
#endregion
}
}
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Cars.aspx.cs" Inherits="HMS.Cars"
MasterPageFile="~/frame.Master" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ContentPlaceHolderID="content" ID="con" runat="server">
<link rel="StyleSheet" href="css/menu.css" type="text/css" media="all">
<asp:ScriptManager ID="sc" runat="server">
</asp:ScriptManager>
<div id="menu">
<ul class="glossymenu">
<li><b>Home</b></li>
<li class="current"><b>Cars</b></li>
<li><b>Boats</b></li>
<li><b>Contact</b></li>
<li><b>Admin</b></li>
</ul>
</div>
<div>
<div>
<asp:UpdatePanel ID="upSearch" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="search">
<fieldset>
<legend>Advanced search</legend>
<table>
<tr>
<td>
Proizvođač:<asp:DropDownList ID="ddlProducer" runat="server" OnSelectedIndexChanged="ddlProducer_Changed"
AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
Model:<asp:DropDownList ID="ddlModel" runat="server" Enabled="false">
</asp:DropDownList>
</td>
<td>
Boja:<asp:DropDownList ID="ddlColor" runat="server">
<asp:ListItem Text="all" Value=""></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
Cena do:
<asp:TextBox ID="txtStartPrice" runat="server" MaxLength="10"></asp:TextBox>
din/dan
</td>
<td>
Number seats:<asp:DropDownList ID="ddlNumber" runat="server">
<asp:ListItem Text="-- --" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
<asp:ListItem Text="5" Value="1"></asp:ListItem>
<asp:ListItem Text="6" Value="2"></asp:ListItem>
<asp:ListItem Text="7" Value="3"></asp:ListItem>
<asp:ListItem Text="8" Value="4"></asp:ListItem>
<asp:ListItem Text="9" Value="2"></asp:ListItem>
<asp:ListItem Text="10" Value="3"></asp:ListItem>
<asp:ListItem Text="11" Value="4"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ID="imbSearch" runat="server" ImageUrl="images/icons/search.png"
Width="32" Height="32" ToolTip="Search by choosen criterions" AlternateText="Search"
OnClick="imbSearch_Click" />
</td>
</tr>
</table>
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<div>
<asp:UpdatePanel ID="upGrid" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:GridView ID="gdvCar" runat="server" OnRowCommand="gdvCar_RowCommand"
OnRowDataBound="gdvCar_DataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div>
<asp:UpdatePanel ID="upTemp" runat="server"><ContentTemplate>
<asp:Panel ID="pnlReserve" runat="server" Visible="false" Width="400" Height="400">
<asp:UpdatePanel ID="upReserve" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ContentTemplate></asp:UpdatePanel>
</div>
</div>
</asp:Content>
You have to recreate the buttons in RowCreated on every Postback, otherwise their events won't fire.
Save what you need in RowDataBound in the ViewState. In the RowCreated recreate them on Postback(RowDatabound will only be called on Databinding) based on the Viewstate value. Then all controls are available in early page-lifecyle to raise their events.
I believe you can do it in a more elegant way, take a look,
<asp:GridView ...>
<Columns>
<asp:BoundField HeaderText="Some Caption" DataField="Column name from the DataReader result"/>
...
<asp:TemplateField HeaderText="Image..">
<asp:Image runat="server" ImageUrl='<%# String.Format("images/car/{0}", Eval("The column name from the DataReader of the cell 7") %>' />
</asp:TemplateField>
<asp:TemplateField HeaderText="ImageButton..">
<asp:ImageButton runat="server" .../>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you don't have to add the buttons and the images in the code and takecare of adding them each time the row is created, you just need to fetch the data from the database and set the DataSource of the gridview, and I think you can also get rid of the code fetching the data and replace it with a SqlDataSource.
Take a look at this article about the GridView,
http://msdn.microsoft.com/en-us/library/aa479353.aspx