How to send extra parameter on SelectedIndexChanged? - asp.net

Is there any way to send extra parameter to SelectedIndexChanged function?
<asp:RadioButtonList
ID="rblMeetingPlace"
SelectedValue = '<%# Bind("intMtgLoc") %>'
*OnSelectedIndexChanged = "Validate('txtMeetPlaceOther')"*
runat="server"
RepeatDirection="Horizontal"
>
<asp:ListItem Value="1">Workshop</asp:ListItem>
<asp:ListItem Value="2">Service provider agency</asp:ListItem>
<asp:ListItem Value="3">Advocacy organization</asp:ListItem>
<asp:ListItem Value="4">Public Space</asp:ListItem>
<asp:ListItem Value="5">Other (specify): </asp:ListItem>
<asp:ListItem Value="" Text="" style="display: none" />
</asp:RadioButtonList>
<asp:TextBox ID="txtMeetPlaceOther" Text='<%# Bind("strMtgLocOth") %>'
runat="server" />
I have couple of radiobuttonlist and I want to enable the textboxes when "Other" is selected.
I am thinking of sending the textbox's id to enable it.
Any idea?

You can easily do it this way:
<asp:radiobuttonlist id="rbl1" runat="server"
RepeatDirection="Horizontal"
AutopostBack="true"
SelectedValue='<%# Bind("intMtgLoc") %>'
OnselectedIndexChanged="rbl1_SelectedIndexChanged">
<asp:ListItem Value="1">Workshop</asp:ListItem>
<asp:ListItem Value="2">Service provider agency</asp:ListItem>
<asp:ListItem Value="3">Advocacy organization</asp:ListItem>
<asp:ListItem Value="4">Public Space</asp:ListItem>
<asp:ListItem Value="5">Other (specify): </asp:ListItem>
<asp:ListItem Value="" Text="" style="display:none" />
</asp:radiobuttonlist>
<asp:textbox id="txtMeetPlaceOther" text='<%# Bind("strMtgLocOth") %>' runat="server" />
<asp:textbox id="TextBox1" enabled="false" runat="server"></asp:textbox>
<asp:textbox id="TextBox2" enabled="false" runat="server"></asp:textbox>
and in code-behind:
protected void rbl1_SelectedIndexChanged(object sender, EventArgs e)
{
*yourValidatorName*.Validate();
if (Convert.ToInt32(rbl1.SelectedValue) == 5)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
}
else
{
TextBox1.Enabled = false;
TextBox2.Enabled = false;
}
}
reply to comment:
First of all you should set OnSelectedIndexChanged for all RadioButtonLists event handlers. Here - rbl_SelectedIndexChanged.
Then in code behind:
protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox[] textboxes = new TextBox[] { TextBox1, TextBox2 };//all your textboxes.
RadioButtonList whoCallEvent = sender as RadioButtonList;
string last = whoCallEvent.ID.ToString().Substring(whoCallEvent.ID.ToString().Length - 1, 1);//get the last symbol of object (TextBox) ID, who call event.
int index = Convert.ToInt32(last);
if (Convert.ToInt32(whoCallEvent.SelectedValue) == 5)
{
textboxes[index - 1].Enabled = true;
}
else
{
textboxes[index - 1].Enabled = false;
}
}
But I think this is conceptually wrong to do it this way. The best way is to create rbl_SelectedIndexChanged for all the radioButtonList you have on my page.

Related

How do i get the value of a datalist item with a button click

I have a dataList with a command button, i want to click the button and obtain the value of a field in the datalist view of the button i have clicked.
I have tried various solutions but keep getting
{"Object reference not set to an instance of an object."}
here is my datalist
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" Width="579px" OnItemCommand = "Datalist1_ItemCommand">
<ItemTemplate>
Epic:
<asp:Label ID="EpicLabel" runat="server" Text='<%# Eval("Epic") %>' />
<br />
ID:
<asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
<br />
Company:
<asp:Label ID="CompanyLabel" runat="server" Text='<%# Eval("Company") %>' />
<br />
Date:
<asp:Label ID="DateLabel" runat="server" Text='<%# Eval("Date") %>' />
<br />
time:
<asp:Label ID="timeLabel" runat="server" Text='<%# Eval("time") %>' />
<br />
NewsItem:
<asp:Label ID="NewsItemLabel" runat="server" Text='<%# Eval("NewsItem") %>' />
<br />
HeadLine:
<asp:Label ID="HeadLineLabel" runat="server" Text='<%# Eval("HeadLine") %>' />
<br />
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Epic", "{0}") %>' Text="Button" />
<br />
</ItemTemplate>
</asp:DataList>
and her is my code behind
public void Datalist1_ItemCommand(object sender, DataListCommandEventArgs e)
{
var button = sender as Button;
/// if (button == null) return;
var dataListItem = button.NamingContainer as DataListItem;
if (dataListItem == null) return;
var currentKey = DataList1.DataKeys[dataListItem.ItemIndex];
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
/// if (myLabel == null) return;
var myLabelText = myLabel.Text;
}
You code do this using the following changes on your code;
on your button control:
<asp:Button ID="Button1" runat="server" CommandName="myCommand" Text="Button" />
on your ItemCommand event:
protected void DataList1_ItemCommand(object source,
DataListCommandEventArgs e)
{
switch (e.CommandName)
{
case "myCommand":
// more code could go here
Label myLabel = (Label)e.Item.FindControl("EpicLabel");
var myLabelText = myLabel.Text;
// more code could go here
break;
}
}
If I am not mistaken, the ID of the control you are looking for is actually called EpicLabel, not just Epic. If myLabel is what the debugger is saying is not set to an instance of an object, this is most likely your problem.
So this line:
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
would need to be:
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "EpicLabel") as Label;

Can not get textbox value inside datalist

I am trying to get the value of textbox "Qty" inside a datalist. It does not work. What is wrong? I have both the CartItem label and the datelist inside the ajax updatepanel. Thanks for any help. Here is my code:
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10"
DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart"
onClick="ButtonAddToCart_Click"/>
<br />
</ItemTemplate>
</asp:DataList>
and here is the button click event. The CartItem has null value:
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
CartItem.Text = DataList1.FindControl("Qty").ToString();
}
TextBox Qty = (TextBox)DataList1.FindControl("Qty");
if(Qty != null)
{
CartItem.Text =Qty.Text;
}
You can use NamingContainer or Parent to access sibling controls
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
var button = sender as Button;
var textbox = button.NamingContainer.FindControl("Qty") as TextBox;
CartItem.Text = textbox.Text;
}
I prefer you to use item_command event of the datalist
do some think like this.
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10" DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart" CommandName="addtocart2" OnCommand="DataList1_ItemCommand"
/>
<br />
</ItemTemplate>
</asp:DataList>
Here is the item_command event that works.
public void DataList1_ItemCommand(object source, System.Web.UI.WebControls.CommandEventArgs e){
TextBox qtytxtbox = DataList1.FindControl("Qty") as TextBox;
}
You can do like this
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
Button ButtonAddToCart= (Button)sender;
DataListItem item = (DataListItem)ButtonAddToCart.NamingContainer;
var textbox = (TextBox)item.FindControl("Qty");
}
try this one
TextBox txtquantity = (TextBox)(e.Item.FindControl("Qty"));
simply use this......You will get the value in txtquantity

CustomValidator ServerValidate dropdownlist

Im trying to validate a dropdownlist and if the selectedValue = "0" then the Isvalid = false but it doesn't seem to be working does any one know what todo here
protected void valCountry_ServerValidate(object sender, ServerValidateEventArgs e)
{
if ((e.Value == "0"))
{
e.IsValid = false;
MasterPage master = Page.Master;
AjaxControlToolkit.ModalPopupExtender popupExtender = (AjaxControlToolkit.ModalPopupExtender)master.FindControl("ModalPopupExtender1");
popupExtender.Show();
}
}
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Value="0" Text="Please Choose" />
<asp:ListItem Value="New Zealand" Text="New Zealand" />
</asp:DropDownList>
<asp:CustomValidator ID="valCountry" runat="server"
ControlToValidate="ddlCountries"
Display="Dynamic"
ErrorMessage="You must select a Country."
SetFocusOnError="true"
ValidationGroup="UserInfo"
OnServerValidate="valCountry_ServerValidate">*</asp:CustomValidator>
Try using ddlCountry.options[ddlCountry.selectedIndex].value instead of e.Value.

RequiredValidation only active when another control contain a value

I have two dropdownlists, if one of them contain a value (not default value, which is empty string), the other should also have a value (like requredvalidator). But if no one has a value the page should validate 'true'.
I cannot solve it with a validation group, because the button that trigger the validation is already triggering other validations.
Could you just use a custom validator control and put your logic in the server side validation method. Keep it in the same validation group.
<asp:CustomValidator ID="valCust" runat="server"
ControlToValidate="ddlControl" ErrorMessage="error Message"
ValidationGroup="Group"
onservervalidate="valCust_ServerValidate" >*</asp:CustomValidator>
code behind
protected void valCust_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = MethodToWorkOutValidation();
}
please check below code snippet.
function EnableDisableValidator() {
var DropDownList1 = document.getElementById('DropDownList1');
var DropDownList2 = document.getElementById('DropDownList2');
var RequiredFieldValidator12 = document.getElementById('RequiredFieldValidator12');
if (DropDownList1.selectedIndex > 0 && DropDownList2.selectedIndex > 0) {
ValidatorEnable(document.getElementById('RequiredFieldValidator12'), true);
}
else {
ValidatorEnable(document.getElementById('RequiredFieldValidator12'), false);
}
}
..........
<asp:DropDownList ID="DropDownList1" runat="server" onchange="EnableDisableValidator();">
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" onchange="EnableDisableValidator();">
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
<div style="display: none;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ControlToValidate="TextBox1"
Enabled="false" ErrorMessage="*************" ></asp:RequiredFieldValidator>
Let me know if any concern

Working with dropdown list & Validation in asp.net

I have got a dropdown list populated with products from a product table. I have a button named ADD Product, so when the user wants to add a new product instead of selecting product from the drop down list, one should click on add new then panel 1 should show which includes a textbox. Panel1 visibility is set to false by default and it should be visible when the user clicks on the button. Also I want a validation on dropdown list and textbox(if panel is visible). Below is the code which is not working :
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<%--<asp:TextBox ID="txtMake" runat="server" CssClass="txtStyle"></asp:TextBox>--%>
<asp:Button ID="btnAdd" runat="server" />
<asp:Panel ID="panel1" Visible="false" runat="server"><asp:TextBox ID="txtAddnew"></asp:TextBox></asp:Panel>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Select a Product" ValidationGroup="insert" ControlToValidate="DropDownList1" ForeColor="Red"></asp:RequiredFieldValidator><br />
codebehind:
protected void btnAdd_Click(object sender, EventArgs e)
{
panel1.Visible = true;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MultiView1.ActiveViewIndex = 0;
DropDownList1.DataSource = caravans.GetProductNames();
DropDownList1.DataBind();
}
}
You can use this concept for validation on dropdownlist. I am given you an example please check this...
<asp:DropDownList runat="server" ID="ddl">
<asp:ListItem Value="-1" Text="Select"></asp:ListItem>
<asp:ListItem Value="1" Text="One"></asp:ListItem>
<asp:ListItem Value="2" Text="Two"></asp:ListItem>
</asp:DropDownList>
<asp:RegularExpressionValidator ID="reg1" runat="server" ControlToValidate="ddl"
Display="Dynamic" ErrorMessage="Select Proper" SetFocusOnError="true" Text="Select Proper"
ValidationGroup="check" ValidationExpression="^\d{0,5}$" />
<asp:Button ID="btn" runat="server" ValidationGroup="check" Text="Submit" />

Resources