How to display textboxes based on selected items in CheckboxList? - c#

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:

Related

Changing a gridview's datasource based on dropdownlist

I'm struggling a lot and I hope someone can help me please.
I have a 4 dropdownlists, a search button and a normal gridview with a basic SQLdataConnection.
The SQLdataConnection is a stored procedure that retrieves 3 tables based on 4 parameters. These 3 tables are then joined together into the gridview.
BUT
One of the dropdownlists has the options of Total, Fast and Slow. So based on which option the user chooses the respective table should be loaded into the gridview when the search button is pressed. (So if total is chosen, the total table should be loaded into the gridview)
I don't know if the SQLdataConnection should be changed with each option to show only the appropriate table.
Below is a copy of the html of the dropdowns and gridview as well as the code behind.
<tr>
<td style="text-align: right" class="pad-right-0">
<asp:DropDownList ID="selSeconds" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selHours" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selMerchantId" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selTableType" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:Button ID="btnSearch" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" OnClick="btnSearch_Click" Text="<%$Resources:Resource, btnSearch %>" />
<asp:ImageButton ID="btnExportToExcel" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" onclick="btnExportToExcel_Click" Text="Export to excel" ImageUrl="images/Excel.png" AlternateText="<%$Resources:Resource, lblExportExcel %>"
CausesValidation="false" />
<asp:RequiredFieldValidator ID="rqrdMerchantId" runat="server" ErrorMessage="<%$Resources:Resource, lblRequired %>" ControlToValidate="selMerchantId" ForeColor="Red" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnMerchantId" runat="server" Value="0" />
<asp:GridView ID="gridSpeedAnalysis" runat="server" DataSourceID="gridSqlConnection">
</asp:GridView>
<asp:SqlDataSource ID="gridSqlConnection" runat="server"></asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] == null || Session["UserType"] == null)
{
Response.Redirect("Login.aspx");
}
LoadDropDowns();
}
private void LoadDropDowns()
{
System.Web.UI.WebControls.ListItem item;
selSeconds.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select Second", "0"));
int index = 1;
for (int Second = 0; Second <= 10; Second++)
{
System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(Second.ToString(), Second.ToString());
selSeconds.Items.Insert(index, li);
index++;
}
item = selSeconds.Items.FindByValue(DateTime.Now.Year.ToString());
selSeconds.SelectedIndex = selSeconds.Items.IndexOf(item);
if (Session["UserType"] != null && (Session["UserType"].ToString().ToLower() == "System Administrator".ToLower()))
{
selMerchantId.DataSource = BOL.MerchantGroup.Load();
selMerchantId.DataTextField = "Description";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = "0", Text = "Select Group" });
rqrdMerchantId.InitialValue = "0";
}
else if (Session["UserType"].ToString().ToLower() == "Head Office".ToLower())
{
BOL.MerchantGroup group = new BOL.MerchantGroup(int.Parse(hdnMerchantId.Value));
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = hdnMerchantId.Value, Text = group.Description });
}
DataTable dt = BOL.Merchant.GetDropdownByMerhcantGroupId(int.Parse(Session["MerchantGroupId"].ToString()));
selMerchantId.DataSource = dt;
selMerchantId.DataTextField = "Name";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Total"});
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Fast" });
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Slow" });
}
protected void btnSearch_Click(object sender, EventArgs e)
{
}

How to get a radio button excluyent in a repeater element?

I have a repeater using for getting an image nad a radio button on the bottom. I want to achieve a combination of this radio button (repeater speaking) with the property of autoexcluyent feature. How can I achieve it?
As far as I got ...
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
With this code I am getting a one radio button per each image but no one autoexcuyent even I am using GroupName property
USING NET FRAMEWORK 4.6.2.
I don't know if easy way to manage this situation however you can manage by below code. It will be good to wrap your contents into update panel so you can prevent page refresh on checkbox changed.
Additionally, IsChecked property being used to initialize checked on page load. You can remove if not required.
.ASPX
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<span>
<asp:RadioButton runat="server" ID="rb1" Checked='<%# Eval("IsChecked") %>' AutoPostBack="true" OnCheckedChanged="rb1_CheckedChanged" Text='<%#Eval("description").ToString()%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<test1> lst = new List<test1>();
lst.Add(new test1() { Id = 1, description = "R1", IsChecked = false });
lst.Add(new test1() { Id = 3, description = "R2", IsChecked = true });
lst.Add(new test1() { Id = 2, description = "R3", IsChecked = false });
lst.Add(new test1() { Id = 4, description = "R4", IsChecked = false });
repeater1.DataSource = lst;
repeater1.DataBind();
}
}
protected void rb1_CheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in repeater1.Items)
{
(item.FindControl("rb1") as RadioButton).Checked = false;
}
(sender as RadioButton).Checked = true;
}
After researching between SOF and a few forums I implemented a quite right solution using JS. I am handling another problem related with OnCheckedChanged´s event on RadioButton...
But the initial issue is fixed.
Forum Solution
I am posting the solution that works for me, using as base as a help coming from a forum, hoping it helps others as well with this bug.
REPEATER.
<asp:Repeater runat="server" ID="repeater1" OnItemDataBound="repeater1_ItemDataBound">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup" OnCheckedChanged="rb1_CheckedChanged"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
BACKEND
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rb1");
string script = "SetUniqueRadioButton('repeater1.*nameGroup',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}

Display calculated value of 2 textbox values to third textbox

I have calculated the two textbox values and displayed successfully it into third textbox but the issues are when I enter value to textbox1 and move to textbox2 the page get reload as I have mentioned AutoPostBack="true" for textbox1 and textbox2 and when I remove this AutoPostBack="true" the calculated value is not displayed in third textbox.
Here is my code behind
protected void txttotal_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txttotal.Text) && !string.IsNullOrEmpty(txtdiscount.Text))
txtgrandtotal.Text = (Convert.ToInt32(txttotal.Text) - Convert.ToInt32(txtdiscount.Text)).ToString();
}
protected void txtdiscount_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txttotal.Text) && !string.IsNullOrEmpty(txtdiscount.Text))
txtgrandtotal.Text = (Convert.ToInt32(txttotal.Text) - Convert.ToInt32(txtdiscount.Text)).ToString();
}
Here is aspx code
<asp:TextBox ID="txttotal" runat="server" CssClass="textstyle" OnTextChanged="txttotal_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:TextBox ID="txtdiscount" runat="server" CssClass="textstyle" OnTextChanged="txtdiscount_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:TextBox ID="txtgrandtotal" runat="server" CssClass="textstyle" ReadOnly="true"></asp:TextBox>
To add the two text box value and show it on third text box you can add them on button click event here is the code
aspx page
<div>
<asp:TextBox runat="server" ID="txt1"></asp:TextBox>
<asp:TextBox runat="server" ID="txt2"></asp:TextBox>
<br />
<asp:Label runat="server" Text="Answer"></asp:Label> <asp:TextBox runat="server" ID="txt3"></asp:TextBox>
<asp:Button runat="server" ID="btn1" Text="CLICK TO ADD" OnClick="btn1_Click"/>
</div>
.cs
protected void btn1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt1.Text) && !string.IsNullOrEmpty(txt2.Text))
{
txt3.Text = (Convert.ToInt32(txt1.Text) + Convert.ToInt32(txt2.Text)).ToString();
}
else {
Response.Write("Please Enter Value");
}
}

Asp .NET Making a value Check on a drop down list from a nother drop down list

I want to force the user to change the selection of the first drop down list IF he/she selected a particular value in the second drop down list.
<asp:DropDownList ID="ddlGxP" runat="server" CssClass="stdDropdownSmall" OnSelectedIndexChanged="ddlGxP_SelectedIndexChanged" AutoPostBack="true" />
<
else
{
}
The above is the first drop down list where the user should select value from "ddlGxP"
The following is the second drop down list where I need to make the check when the user make a selection, I have to check on the first drop down.
<div class="divStandard">
<asp:Label ID="Label23" runat="server" CssClass="stdLabel">nalized Method <span class="mandatory"> *</span></asp:Label>
<asp:DropDownList ID="ddlFinalizedMethod" runat="server" CssClass="stdDropdown" />
<asp:CustomValidator ID="cvFinalizedMethod" runat="server" ControlToValidate="ddlFinalizedMethod" InitialValue="0" OnServerValidate="cvFinalizedMethod_ServerValidate"
CssClass="RequiredFieldError" ErrorMessage=" ! Please select another GxP Standard" />
} else {
<asp:TextBox ID="txtFinalizedMethodDisabled" runat="server" CssClass="stdTextboxSmallDisabled" Enabled="false" />
}
</div>
i don't have enough reputation so here is my comment.
i just want to clarify the problem in basic terms.
your design view consists of two dropdownlists.
you make a selection on dropdownlist1, its selectedindexchanged is triggered performing some sort of action.
you now make a selection on dropdownlist2, its selectedindexchanged is triggered and performs some sort of manipulation on dropdownlist1, either changing its contents or selected value;
SORRY FOR THE WAIT, I MADE SOME SIMPLE ERRORS DUE TO FORGETTING SOME THINGS;
The ANSWER!!!!
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
onselectedindexchanged="ddl2_selectindexchange">
</asp:DropDownList>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> str = new List<string>();
str.Add("red");
str.Add("blue");
str.Add("black");
List<string> str2 = new List<string>();
str2.Add("red");
str2.Add("blue");
str2.Add("black");
DropDownList1.DataSource = null;
DropDownList1.DataSource = str;
DropDownList1.DataBind();
DropDownList2.DataSource = null;
DropDownList2.DataSource = str2;
DropDownList2.DataBind();
}
}
protected void ddl2_selectindexchange(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
ddl = sender as DropDownList;
ListItem li = new ListItem();
li = ddl.SelectedItem;
string s = li.Text;
Label1.Text = s;
}

ASP.NET Passing asp:Repeater value to asp:Button CssClass attribute

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;
}

Categories

Resources