I have a payment method repeater that contains a button. We have new button styles that need to be applied. The new button style changes based on a btnMode setting in the database which is set to a string representing a CSS class selector. The CSS works fine.
I put this in the ASPX page:
<asp:Button ID="btnEdit"
runat="server"
ClientIDMode="Static"
CssClass='<%# Eval("btnMode") %>'
Text="edit"
CommandName="ChangePaymentProfile"
CommandArgument='<%# Eval("PaymentSourceId") + "|" + Eval("AuthNetPaymentProfileId")%>' />
In the ASPX.cs
//Command Button Clicked: Change Payment Method
else if (e.CommandName.ToLower().Equals("changepaymentprofile"))
{
hdChangeYN.Value = "Y";
showAddPaymentForm();
//display billing address of selected card
hsParams.Add("CustomerId", User.Identity.Name);
hsParams.Add("PaymentSourceId", strPaymentSourceId);
DataTable dt = DbHelper.GetDataTableSp("234_accountAddress__ByPaySourceId", hsParams);
if (dt.Rows.Count > 0)
{
tbFistName.Text = dt.Rows[0]["FirstName"].ToObjectString();
tbLastName.Text = dt.Rows[0]["LastName"].ToObjectString();
inputAddress1.Text = dt.Rows[0]["Address"].ToObjectString();
inputAddress2.Text = "";
string strCountryCd = dt.Rows[0]["CountryCd"].ToObjectString();
ddlCountry_Update(strCountryCd); //Update Country & State DDL because Country can be a foreign country
ddlCountry.SelectedValue = strCountryCd;
inputCity.Text = dt.Rows[0]["City"].ToObjectString();
ddlState.SelectedValue = dt.Rows[0]["StateProvinceId"].ToObjectString();
inputZipcode.Text = dt.Rows[0]["Zipcode"].ToObjectString();
ddlCardType.SelectedValue = dt.Rows[0]["CardType"].ToObjectString();
}
}
When I load the page in the browser the <%# Eval("btnMode") %> does not get resolved to a value. I see this when I open the inspector:
<input
id="btnEdit"
class="<%# Eval("btnMode") %>"
type="submit"
name="ctl00$ctl00$ContentPlaceHolderFront$ContentPlaceHolderFront$rptList$ctl01$btnPrimary"
value=""
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl00$ContentPlaceHolderFront$ContentPlaceHolderFront$rptList$ctl01$btnPrimary", "", true, "", "", false, false))" >
It is important to point out that this attribute CommandArgument='<%# Eval("PaymentSourceId") %>' does work, and btnMode does contain valid data.
As I wrote in a comment, not all properties in Asp.Net controls can be databound. CssClass is one that cannot be databound.
To get around this, you can add an OnItemDataBound event handler to the repeater where the Button is. In the event handler you can then user the e.Item.DataItem to get the value you want and set it as the CssClass on the button. Sample code:
<asp:Repeater ID="RepeaterTest" runat="server" OnItemDataBound="RepeaterTest_ItemDataBound">
<ItemTemplate>
<div>
<asp:Button ID="TestButton" runat="server" Text='<%# Eval("someText") %>'/>
</div>
</ItemTemplate>
</asp:Repeater>
and code behind:
protected void Page_Load(object sender, EventArgs e)
{
var testData = Enumerable.Range(1, 10).Select(i => new { someText = "Button " + i.ToString() }).ToList();
RepeaterTest.DataSource = testData;
RepeaterTest.DataBind();
}
protected void RepeaterTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
dynamic foo = e.Item.DataItem;
((Button)e.Item.FindControl("TestButton")).CssClass = foo.someText;
}
Related
I'm trying to display textboxes based on the checkboxlist items that the user has selected. I have 15 items in my checkboxlist with a textbox which corresponds to each when selected. I've made this code but I am unsure how to proceed. My goal is to look through the items in my checkboxlist and whenever it finds a selected item, it will make visible the div which displays the textbox. The textbox will have almost the same name as it's check box list equivalent. My problem is Im not quite sure how to take that value and making it so that it looks for the textbox control with the same name and display.
This is what I have so far:
{
foreach(ListItem item in cblReasonSeekingServices.Items)
{
if (item.Selected == true)
{
string strControlName = item.Value;
string strSpaceRemoved = Regex.Replace(strControlName, " ", "");
((TextBox)FindControl("pnl" + strSpaceRemoved)).Visible = true;
}
}
}
EDIT: I'm able to run the code now without any error messages however, the textbox control does not display. Am I missing anything?
foreach(ListItem item in cblReasonSeekingServices.Items)
{
if (item.Selected == true)
{
string strControlName = item.Value;
string strSpaceRemoved = Regex.Replace(strControlName, " ", "");
string test = ("tb" + strSpaceRemoved);
TextBox tBox = this.Master.FindControl("body").FindControl("tbBehavioralDifficulties") as TextBox;
tBox.Visible = true;
}
Hum, ok, say we have 5 text box, and then
So, say this:
<div style="float:left;width:20%">
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
</div>
<div style="float:left;width:20%">
<asp:TextBox ID="TextBox1" runat="server" Text="Text1"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox2" runat="server" Text="Text2"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox3" runat="server" Text="Text3"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox4" runat="server" Text="Text4"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox5" runat="server" Text="Text5"> </asp:TextBox> <br />
</div>
<div style="clear:both;height:20px">
</div>
<asp:Button ID="Button1" runat="server" Text="Show selected" OnClick="Button1_Click" />
And code behind is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 1; i <= 5; i++)
{
ListItem OneItem = new ListItem("Choice #" + i, i.ToString());
CheckBoxList1.Items.Add(OneItem);
// hide the text box
string sTbox = "TextBox" + i;
TextBox Tbox = Page.FindControl(sTbox) as TextBox;
Tbox.Visible = false;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem Choice in CheckBoxList1.Items)
{
string sTbox = "TextBox" + Choice.Value;
TextBox Tbox = Page.FindControl(sTbox) as TextBox;
Tbox.Visible = Choice.Selected;
}
}
So, we get this then - select a few check box, hit button:
I have a repeater, one column of which contains a textbox on which is attached a JQuery datepicker along with an update button. So a user uses the datepicker to change the date, clicks update and it writes to the database.The original date and the record id are stored in hidden fields.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hidThisID" Value='<%# Eval("orderID") %>' runat="server" />
<asp:HiddenField ID="hidPrevDueDate" Value='<%# Eval("Duebeforedate", "{0:dd/MM/yyyy}") %>' runat="server" />
<input type="text" class="form-control fc-datepicker duedateinput" style="width: 150px" value='<%# Eval("Duebeforedate", "{0:dd/MM/yyyy}") %>' runat="server" id="fccd" readonly />
<asp:LinkButton ID="btnDateUpdate" OnClick="btnDateUpdate_Click" CssClass="btn btn-primary btn-sm" runat="server" ToolTip="Approved"> Update </asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
which calls this function
protected void btnDateUpdate_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
HtmlInputText htmlDueDate = (HtmlInputText)item.FindControl("fccd");
HiddenField hidID = (HiddenField)item.FindControl("hidThisID");
HiddenField hidOldDate = (HiddenField)item.FindControl("hidPrevDueDate");
DateTime prevDueDate = Convert.ToDateTime(hidOldDate.Value.ToString());
DateTime newDueDate = Convert.ToDateTime(htmlDueDate.Value.ToString());
string ID = hidID.Value;
if (prevDueDate != newDueDate)
{
string query = "update [tblOrders] set Duebeforedate=CONVERT(datetime,'" + newDueDate.ToString() + "', 103) where [orderID] = '" + ID + "'";
//database stuff here
}
}
}
However, the newDueDate variable still holds the original due date. Consequently the old and new dates match and so the database doesn't get updated. How do I get it to store the new value?
For two-way data binding you need to use the Bind keyword instead of Eval
Fixed it, it wasn't the btnUpdate function at all, I'd forgotten this check -
if (!IsPostBack)
{
//bind the repeater
}
I have a repeater that in it has one dropdown list and one linkbutton.
I want to get the selected value of the dropdown list by CommandArgument in linkbutton, but it just knows default value of dropdown list.
My code :
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="Page_Load2"OnItemCommand="list_ItemCommand" >
<ItemTemplate>
<asp:DropDownList ID="dlPricelist" CssClass="width100darsad dropdownlist" runat="server" AutoPostBack="true" ViewStateMode="Enabled" >
</asp:DropDownList>
<asp:LinkButton ID="btnAddToCart" runat="server" class="btn btn-success btnAddtoCardSinglepage" CommandArgument='<%#Eval("id") %>' CommandName="addtocard">اضافه به سبد خرید</asp:LinkButton>
<asp:Label ID="xxxxxx" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load2(object sender, RepeaterItemEventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"].ToString();
DataSet dsselectcategory = BLLTour.left3join(id.Trim().ToString());
var dlPricelist = (DropDownList)e.Item.FindControl("dlPricelist");
dlPricelist.DataSource = dsselectcategory.Tables[0];
dlPricelist.DataTextField = "pricelistPrice";
dlPricelist.DataValueField = "priceid";
dlPricelist.DataBind();
}
}
protected void list_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtocard")
{
foreach (RepeaterItem dataItem in Repeater1.Items)
{
Label xxxxxx = (Label)e.Item.FindControl("xxxxxx");
LinkButton btnAddToCart = (LinkButton)e.Item.FindControl("btnAddToCart");
xxxxxx.Text = ((DropDownList)dataItem.FindControl("dlPricelist")).SelectedItem.Text; //No error
}
}
}
I don't know how I should fix it.
You are using very old technology to show data that's not appropriate.
But if you are serious to use it, you must use FindControll method in ItemTemplate of your repeater control. You should find dropdownlist first, and then cast it to a object to be able to use it's value.
I've struggled a lot with how to show a modal panel on click on a button inside a grid view.
To context: I have a data row with a string field that can contain a simple text or a base 64 encoded image, so I'm using a custom template to define when to show the raw content or a button "View Image". This image will be opened on a modal panel that should rise up on button click.
This is the Panel I've created as a control (ascx):
<asp:Panel ID="pnlModalOverlay" runat="server" Visible="true" CssClass="Overlay">
<asp:Panel ID="pnlModalMainContent" runat="server" Visible="true" CssClass="ModalWindow">
<div class="WindowTitle">
<asp:Label ID="lbTitle" runat="server" />
</div>
<div class="WindowBody">
<asp:Panel ID="pnlContent" runat="server" Visible="true">
<asp:Image ID="imgContent" runat="server" CssClass="ImageView" />
</asp:Panel>
<div class="Button">
<asp:Button ID="btnOk" runat="server" class="btn btn-default " Text="Close" OnClientClick="loadingPanel.Show();" />
</div>
</div>
</asp:Panel>
</asp:Panel>
And this is the page and ASPxGridView where I wanna use it:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<div style="margin-top: 12px;">
<asp:Button type="button" ID="btnShowImage" AutoPostBack="true" class="btn btn-default navbar-right" Text="Show Image"
runat="server" Style="margin-left: 5px;" OnClientClick="loadingGridPanel.Show();" />
</div>
<!-- Some data filter controls -->
<MyWorkspace:AlertModal ID="alertModal" runat="server" Visible="false" />
<MyWorkspace:ImageModal ID="imageModal" runat="server" Visible="false" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="mainGrid" />
</Triggers>
</asp:UpdatePanel>
<MyWorkspace:GridViewWrapper ID="mainGrid" runat="server" Visible="true" />
Codebihind:
public partial class MyPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnShowImage.Click += new EventHandler(ShowImage); // This call works fine
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
mainGrid.CanEditItems = true;
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Id", template = new LinkColumn(CreateParentLink, "Go to parent") });
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Value", template = new ButtonColumn(ShowImage, "View Image") }); // This one doesn't works
}
}
catch (Exception ex)
{
modalAlerta.Show("Page_Load", ex.Message, false, false, "");
}
}
void ShowImage()
{
modalImagem.Show(); // Set Modal's Visible property to True
// UpdatePanel1.Update(); <-- Tryin' force it to work with no success
}
}
The ButtonColumn template creation:
public class ButtonColumn : System.Web.UI.ITemplate
{
private Action action;
private string controlId;
private string tooltip;
public ButtonColumn(Action onClick, string toolTip)
{
this.action = onClick;
this.controlId= "btnShowImage";
this.tooltip = toolTip;
}
public void InstantiateIn(System.Web.UI.Control container)
{
GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
if (System.Text.RegularExpressions.Regex.IsMatch(gridContainer.Text, "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"))
{
ImageButton button = new ImageButton();
button.ID = idControle;
button.ImageUrl = "/Images/html5_badge_64.png";
button.Width = 20;
button.Height = 20;
button.ToolTip = tooltip;
button.Click += (s, a) =>
{
if (onClick != null)
onClick();
};
container.Controls.Add(button);
}
else
{
Label label = new Label()
{
Text = gridContainer.Text,
ToolTip = tooltip
};
container.Controls.Add(label);
}
}
}
The method's call at the click of btnShowImage button works fine. But when I do the same call by one ImageButton (or button) inside the gridview it doesn't work. Both calls reach the ShowImage method.
Any help would be appreciated. Thank you all.
EDIT 1:
The GridView is encapsulated in GridViewWrapper (there I build the columns dynamically using a combination of class's properties gotten by reflection and stored metadata), this class have too much code to share here and I do not think it's the reason. Also, I've executed in debug mode and passed thru it step by step every relevant method inside this one.
The column add method:
CustomColumnTemplate customTemplate = CustomTemplates.FirstOrDefault(f => f.columnName == metadata.ColumnIdName);
gridView.Columns.Add(new GridViewDataColumn()
{
FieldName = metadata.ColumnIdName,
VisibleIndex = GetVisibleIndexByColumnIdName(metadata.ColumnIdName),
Caption = metadata.Caption,
Width = new Unit(DefaultColumnWidth, UnitType.Pixel),
DataItemTemplate = customTemplate == null ? null : customTemplate.template
});
I've made sure the ShowImage method is being hitten, but it behaves like the UpdatePanel1 isn't have been updated
The ASPxGridView stores information about columns in ViewState, but does not save information about column templates. This is made on purpose since templates can be very complex and their serialization makes ViewState very huge.
So, if you create columns with templates at runtime, disable ViewState:
ASPxGridView.EnableViewState="false"
and create columns on every callback:
//if (!IsPostBack)
//{
mainGrid.CanEditItems = true;
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Id", template = new LinkColumn(CreateParentLink, "Go to parent") });
mainGrid.CustomTemplates.Add(new CustomColumnTemplate { columnName = "Value", template = new ButtonColumn(ShowImage, "View Image") }); // This one doesn't works
//}
You used code below:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="mainGrid" />
</Triggers>
According to this article, in asp:AsyncPostBackTrigger If the EventName property is not specified, the DefaultEventAttribute attribute of the control is used to determine the default event. For example, the default event for the Button control is the Click event.
mainGrid control created by GridViewWrapper that it doesn't connected to controls that are in mainGrid.
Updatepanel tries to register async trigger for the mainGrid control which is outside the panel but it can't do it.
solution:
I think solution of this problem is update Updatepanel in ShowImage() method.
I want to do a task in which i want that using findControl during the use of webusercontrol on web form to get value of webusercontrol on main page I mean, I've created a webusercontrol and have used on web form. In webusercontrol.ascx page i use a textbox, calendar, and dropdownlist. Now I want to get value(which i choose from txtbox, ddl etc) should be display on main page. I mean, I want to use a button on default.aspx page and in a variable want to store value of txtbox, calendar etc. and using a FindControl want to get these values on main page. How I can do this plz help me by code plz I'm new in programing.
This is the code of ascx page
<%# Control Language="C#" ClassName="CalendarUserControl" %>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox> <br />
<asp:Calendar ID="Calendar1" runat="server" BackColor="Beige" >
</asp:Calendar>
<br/>
<asp:DropDownList ID="ddlthings" runat="server">
<asp:ListItem> Apple</asp:ListItem>
<asp:ListItem> Banana</asp:ListItem>
<asp:ListItem> Mango</asp:ListItem>
<asp:ListItem> Grapes</asp:ListItem>
</asp:DropDownList>
default.aspx page
<div>
<uc1:CalendarUserControl ID="CalendarUserControl1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="btn_Click" Text="Button" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
Define properties in your user control, that will return values of controls you want. For example
public partial class CalendarUserControl: UserControl
{
// this is code-behind of your user control
public string Data
{
get {return txtData.Text;}
}
public DateTime CalendarDate
{
get {return Calendar1.SelectedDate;}
}
// same approach for drop down list ddlthings
}
Then in your aspx page, just read those values, for example in your btn_Click event handler
protected void btn_Click(object sender, EventArgs e)
{
var textBoxValue = CalendarUserControl1.Data;
var calendarValue = CalendarUserControl1.CalendarDate;
//....
}
i did it, just write these lines in default.cs
protected void btn_Click(object sender, EventArgs e)
{
TextBox myLabel = (TextBox)CalendarUserControl1.FindControl("txtData");
string x = myLabel.Text.ToString();
Calendar c = (Calendar)CalendarUserControl1.FindControl("Calendar1");
string date = c.SelectedDate.ToString();
DropDownList b = (DropDownList)CalendarUserControl1.FindControl("ddlthings");
string ddl = b.SelectedValue;
Label1.Text = "Your text is: " + x + "<br />"+ " Your Selected Date is: " + date + "<br />"+ " Your Selected Item is: " + ddl;
}