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: انقر فوق لتقديم
Related
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();
}
}
I'm using jQuery's AutoComplete on an ASP.NET DropDownList, the user can select a value and submit for entry into the DB. But they must also be able to type in a value, and I can't seem to be able to access that value in the code behind.
Heres the jQuery:
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = this.input = $("<input id='txtOptValue'>")
.insertAfter(select)
.val(value)
.autocomplete({
delay: 0,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
//$(this).val("");
// select.val("");
// input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(input)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function () {
this.input.remove();
this.button.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
So this takes my DropDownList, hides it, creates an input field acting as my select and also enables me to type in values.. This is my DropDownList:
<asp:FormView ID="frmCreateOptionValue" runat="server" DataKeyNames="OptionValueID"
DataSourceID="OptionSetValues_DS" DefaultMode="Insert"
oniteminserting="frmCreateOptionValue_ItemInserting">
<InsertItemTemplate>
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th>
Add Option Set Value:
</th>
<td>
<div class="ui-widget" runat="server" id="addOptValue">
<asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("OptionValueID") %>'>
<asp:ListItem Value="" Text="Select One..." />
</asp:DropDownList>
<asp:ObjectDataSource ID="OptionValues_DS" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetDataBy1" TypeName="PurekbbDataSetTableAdapters.tblOptionValueTableAdapter">
<SelectParameters>
<asp:QueryStringParameter Name="oID" QueryStringField="optionSetID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</div>
</td>
<td>
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
CssClass="form-submit" />
</td>
</tr>
</table>
</InsertItemTemplate>
</asp:FormView>
And when the user inserts an item:
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
string ovName = ((TextBox)frmCreateOptionValue.FindControl("txtOptValue")).Text;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Is where I am stuck, how can I get the value from that HTML input field generated in jQuery?
How can this be achieved, it's killing me ;)
you can get the value of this text box using javascript and save it in a hidden field then read the hidden field value from code behind
put this inside javascript
$('#HiddenFieldID').val($('#txtOptValue').val());
then code behind will look like this
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
string ovName = ((HiddenField)frmCreateOptionValue.FindControl("HiddenFieldID")).Value;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Heres the solution to this one, using a HiddenField:
Add onblur to the dynamically created input:
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = this.input = $("<input id='txtOptValue' onblur='JavaScript:copyValue()'>") ....
Add HiddenField and jQuery to the page:
<asp:HiddenField runat="server" ID="hfoValue" EnableViewState="true" ClientIDMode="Static" />
<div class="ui-widget" runat="server" id="addOptValue">
<script type="text/javascript" language="javascript">
function copyValue() {
var theVal = $('#txtOptValue').val();
//alert('Copyng ' + theVal);
$('#hfoValue').val(theVal);
//alert('copied');
}
</script>
<asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("OptionValueID") %>'>
<asp:ListItem Value="" Text="Select One..." />
</asp:DropDownList> ...
Finally access the value from the HiddenField:
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! FOUND THE VALUE :)
string ovName = ((HiddenField)frmCreateOptionValue.FindControl("hfoValue")).Value;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Thanks to #Miroprocessor for helping to solve this one
My problem is this: when I change the values manually on a slider, that is input the value in the textbox instead of dragging the slider, the page is not reloaded so no change is visible.
I've tried adding a "OnTextChanged"-listener but that doesn't work.
I thought setting AutoPostBack="true" would cause the page to reload when inputting values, but that didn't work either.
The slidercode:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="IntervalSlider.ascx.cs" Inherits="DynamicForm.UserControls.Filter.IntervalSlider" %>
<tr>
<td>
<asp:Label runat="server" ID="lblHeader"></asp:Label><asp:Image runat="server" ID="infoImg" Visible="false" ImageUrl="~/HTML/icons/info_16.png" />
</td>
<td class="filterSpacerCol"> </td>
<td>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:TextBox ID="txtMin" size="6" style="text-align:right;" runat="server" AutoPostBack="true" value=""></asp:TextBox>
</td>
<td width="150px"><div runat="server" id="divSlider" style="margin-top:0px"> <asp:TextBox ID="txtCurrentValue" runat="server" AutoPostBack="true" OnTextChanged="txtCurrentValue_TextChanged" value="20" style="display:none;" />
<ajax:MultiHandleSliderExtender ID="MultiHandleSliderExtenderMinMax" runat="server" Minimum="0" Maximum="10" TargetControlID="txtCurrentValue">
<MultiHandleSliderTargets>
<ajax:MultiHandleSliderTarget ControlID="txtMin" />
<ajax:MultiHandleSliderTarget ControlID="txtMax" />
</MultiHandleSliderTargets>
</ajax:MultiHandleSliderExtender>
</div>
</td>
<td>
<asp:TextBox ID="txtMax" size="6" style="text-align:right;" runat="server" AutoPostBack="true" value="" />
</td>
</tr>
</table>
</td>
</tr>
underlying code:
public partial class IntervalSlider : System.Web.UI.UserControl, IRange
{
protected void Page_Load(object sender, EventArgs e)
{
lblHeader.Text = HttpUtility.HtmlEncode(HeaderText);
if ((ToolTipText ?? "") != "")
{
infoImg.Visible = true;
infoImg.ToolTip = ToolTipText;
lblHeader.ToolTip = ToolTipText;
}
divSlider.Attributes.Add("title", ToolTipText);
txtMax.ToolTip = ToolTipText;
txtMin.ToolTip = ToolTipText;
foreach (AjaxControlToolkit.MultiHandleSliderTarget target in MultiHandleSliderExtenderMinMax.MultiHandleSliderTargets)
target.ControlID = MultiHandleSliderExtenderMinMax.Parent.FindControl(target.ControlID).ClientID;
}
public string HeaderText { get; set; }
public string ToolTipText { get; set; }
protected void txtCurrentValue_TextChanged(object sender, EventArgs e)
{
//FilterChanged(sender, e);
}
public event EventHandler FilterChanged;
public string MaxFilterValue
{
get { return txtMax.Text; }
}
public int Minimum
{
get { return MultiHandleSliderExtenderMinMax.Minimum; }
set
{
MultiHandleSliderExtenderMinMax.Minimum = value;
txtMin.Text = value.ToString();
}
}
public int Maximum
{
get { return MultiHandleSliderExtenderMinMax.Maximum; }
set {
int minValue = value;
MultiHandleSliderExtenderMinMax.Maximum = minValue;
txtMax.Text = minValue.ToString();
}
}
public string MinFilterValue
{
get { return txtMin.Text; }
}
}
}
Anyone have a clue on how to solve this?
I solved it with this bit of JavaScript-code at the end of the Page Load of the IntervalSelector:
string jscript = #"
var filterSearchTimerId = 0;
var previousFilterValues = new Array();
function SetFilterSearchTimeout ( textBox, executeThis, delayValue ) {
if (textBox.value == previousFilterValues[textBox.id]) { return; }
previousFilterValues[textBox.id] = textBox.value;
if (filterSearchTimerId != 0) { clearTimeout(filterSearchTimerId); }
filterSearchTimerId = setTimeout(executeThis, delayValue);
}
";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetFilterSearchTimeout", jscript, true);
string formatString = #"javascript:SetFilterSearchTimeout(this, '__doPostBack(\'{0}\',\'\')', {1})";
txtMin.Attributes.Add("onkeyup", string.Format(formatString, txtMin.UniqueID, "500"));
txtMin.Attributes.Add("onpaste", string.Format(formatString, txtMin.UniqueID, "5"));
txtMin.Attributes.Add("oncut", string.Format(formatString, txtMin.UniqueID, "5"));
txtMin.Attributes.Add("onchange", string.Format(formatString, txtMin.UniqueID, "0"));
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
I have an ASP.NET page where I have a button When a user clicks on the button,I will check whether the user has logged in or not.If not logged in I will show a modal popup to login (using jQueryUI). I have placed one textbox(txtPassword) and one button(btnLogin) control in the Div which will be shown by the jQueryDialog.But in btnLogin's Click event, I am not able to read the Text value entered in the textbox txtPassword
The below is my code
<form id="form1" runat="server">
<div>
<br />
<asp:TextBox ID="txtModelId" runat="server" Text=""></asp:TextBox><br />
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" />
<br />
<asp:Label ID="lblUserMsg" runat="server" Text="Label"></asp:Label></div>
<div id="divContentHolder">
<div class="demo">
<div id="dialog" title="Login with your TradeIn Account">
<p id="validateTips">Enter your EmailId & password</p>
<fieldset>
<label for="email">Email</label>
<asp:TextBox ID="txtEmail" CssClass="text ui-widget-content ui-corner-all" runat="server" ></asp:TextBox>
<label for="password">
<asp:TextBox ID="TextBox1" runat="server" Text="sample"></asp:TextBox>Password</label>
<asp:TextBox ID="txtPassword" CssClass="text ui-widget-content ui-corner-all" runat="server" ></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" UseSubmitBehavior="false"/>
</fieldset>
</div><!--dialog-->
</div><!--demo-->
</div><!--divContentHolder-->
</form>
Server side Code
protected void btnGo_Click(object sender, EventArgs e)
{
CheckUserLoggedIn();
}
private void CheckUserLoggedIn()
{
if (Session["username"] != null)
{
Response.Write("Logged in user");
ClientScript.RegisterHiddenField("isAuthenticated", "true");
}
else
{
ClientScript.RegisterHiddenField("isAuthenticated", "false");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string txtSample= TextBox1.Text; // this is showing the value 'sample'
string txtPass= txtPassword.Text; // this is showing null
if (txtPass == "shyju")
{
Session["username"] = txtPassword.Text;
Response.Redirect("TestingModal.aspx");
}
}
My java script code to render the dialog
$(function() {
var name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $("#validateTips");
function updateTips(t) {
tips.text(t).effect("highlight",{},1500);
}
function checkLength(o,n,min,max) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass('ui-state-error');
updateTips("Length of " + n + " must be between "+min+" and "+max+".");
return false;
} else {
return true;
}
}
function checkRegexp(o,regexp,n) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass('ui-state-error');
updateTips(n);
return false;
} else {
return true;
}
}
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 300,
modal: true,
buttons: {
'Create an account': function() {
var bValid = true;
allFields.removeClass('ui-state-error');
bValid=true;
if (bValid) {
/*$('#users tbody').append('<tr>' +
'<td>' + name.val() + '</td>' +
'<td>' + email.val() + '</td>' +
'<td>' + password.val() + '</td>' +
'</tr>'); */
alert("Check User Credentials")
$(this).dialog('close');
}
},
Cancel: function() {
$(this).dialog('close');
}
},
close: function() {
allFields.val('').removeClass('ui-state-error');
}
});
$('#create-user').click(function() {
$('#dialog').dialog('open');
})
.hover(
function(){
$(this).addClass("ui-state-hover");
},
function(){
$(this).removeClass("ui-state-hover");
}
).mousedown(function(){
$(this).addClass("ui-state-active");
})
.mouseup(function(){
$(this).removeClass("ui-state-active");
});
var isAuthenticated = $("#isAuthenticated").val();
if (isAuthenticated && isAuthenticated == "false")
{
// Display the modal dialog.
$("#dialog").dialog("open");
}
});
I had hard coded the text properties value of TextBox1 as 'sample' in the HTML part of my ASPX file .In button click event i am getting it.But the other textbox,txtPassword 's Text property is giving me null value
Please guide me to go ahead
Thanks in advance
Try to get txtPassword value like this
string val=txtPassword.Attributes["value"].ToString();