have a radiobutton list which I am filling with Strings and would like to know how to get in a given time the value of the selected element and throw it into a String for example. but with the command SelectedValue and SelectedItem only have null values.
This radio button list is filled several times during the execution of the same page.
//Where do you fill the RadioButtonList
public void MostraImagensCarrefadas()
{
List<String> files = new manFile().getListFilesForDirectory(this, MAE.DIRETORIO_TEMP_IMG);
rbImagemPrincipal.Items.Clear();
if (files != null)
{
foreach (String item in files)
{
rbImagemPrincipal.Items.Add(new ListItem(item));
}
}
}
//As it is in aspx
<div>
<asp:RadioButtonList ID="rbImagemPrincipal" runat="server" RepeatDirection="Vertical" AutoPostBack="false" OnSelectedIndexChanged="rbImagemPrincipal_SelectedIndexChanged"></asp:RadioButtonList>
//where only encounter null values when trying to get the selected item (clicked)
//Nothing I do is the value obtained direferente null.
if (rbImagemPrincipal.SelectedItem != null)
{
if (rbImagemPrincipal.SelectedItem.ToString() == str)
{
imagem.imagemPrincipal = "SIM";
}
}
It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RBL
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}
First of all, this is the page let you know the value, not the application is getting it.
So, you need a ScriptManager and Timer, both are Ajax extensions. Add them to the page.
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Interval = 2000; // set your interval
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int result = RadioButtonList1.SelectedIndex;
}
result is your radiobuttonlist selection index. Use it to select item from list.
Related
I am creating a little ASP.NET app and have a problem with one field value.
I have defined my enum in a class:
class Column
{
public enum Type {
Undefined = 0,
Integer = 1,
ShortDate = 2,
Etc = 3 }
// some other stuff
}
The app contains some controls to enter properties of a column, namely a dropdownlist for choosing the column type and some unimportant others. And when all properties are properly entered, SaveButton in enabled to save the column type info into a listbox. My Default.aspx.cs contains:
private Column.Type selectedType;
protected void Page_Load(object sender, EventArgs e)
{
// fill the ColumnTypeDropDownList (from the Column.Type enum)
if (!IsPostBack)
{
foreach (Column.Type ct in Enum.GetValues(typeof(Column.Type)))
{
ColumnTypeDropDownList.Items.Add(new ListItem(ct.ToString()));
}
}
}
protected void ColumnTypeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
PrepareToSave();
}
// also called from other controls events, therefore in a separate method
private void PrepareToSave()
{
// control if all needed properties are entered and set the field
if ((ColumnNameTextBox.Text != "") && (ColumnTypeDropDownList.SelectedValue != Column.Type.Undefined.ToString()))
{
foreach (Column.Type ct in Enum.GetValues(typeof(Column.Type)))
{
if (ct.ToString() == ColumnTypeDropDownList.SelectedValue) selectedType = ct;
}
SaveButton.Enabled = true;
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
ColumnsListBox.Items.Add(selectedType.ToString()); // always writes "Undefined"
}
The problem is that it always writes "Undefined" into the listbox, even though another type was selected from the dropdownlist. I tried to add the item into the listbox inside the PrepareToSave() method and that works correctly, but I need it outside. On the other hand, the condition controlling if any other value than Undefined is selected from the dropdownlist works well. It seems that the field selectedType has the correct selected value only inside the PrepareToSave() method.
AutoPostBack of all the controls is enabled.
Am I missing something about the enums or do you have any tips how to fix it? Thanks.
Your problem is in the line...
ColumnTypeDropDownList.Items.Add(new ListItem(ct.ToString()));
..namely in new ListItem(ct.ToString()). When you use this constructor of the ListItem class, you create an item with Value set to null. Later you compare against the value:
if (ct.ToString() == ColumnTypeDropDownList.SelectedValue) selectedType = ct;
Since Value of each of the items is null, ColumnTypeDropDownList.SelectedValue is also null and your comparison fails. That should be also easily figured out in a debugger.
The correct list item constructor for you is
ListItem listItem = new ListItem(ct.ToString(), ct.ToString());
As an additional issue, you have to call PrepareToSave in SaveButton_Click, since the selectedType field will have lost its value across requests. PrepareToSave will rebuild that value.
That's most probably because of your if condition as pointed below
if ((ColumnNameTextBox.Text != "") && (ColumnTypeDropDownList.SelectedValue != Column.Type.Undefined.ToString()))
{
Instead of ColumnNameTextBox.Text != "" use !string.IsNullOrEmpty(ColumnNameTextBox.Text)
Just another tip:
Use GetNames instead of GetValues in your foreach loop:
foreach (var ct in Enum.GetNames(typeof(Column.Type)))
{
//do your stuff.
}
If you want to use AutoPostBack ...
Add a hidden control to your page.
In your PrepareToSave(); method you just can add the selectetType like yourControlName.Text = ct;
And change your save handler to this ....
protected void SaveButton_Click(object sender, EventArgs e)
{
// Read the value of the hidden control
ColumnsListBox.Items.Add(yourControlName.Text);
}
I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"
I am filling DDL dynamically :
<asp:DropDownList ID="ddlTimeZone" Style="width: auto" runat="server" >
</asp:DropDownList>
With this function :
private void initTimeZone()
{
var timeZones = TimeZoneInfo.GetSystemTimeZones();
foreach (TimeZoneInfo timeZone in timeZones)
{
ListItem item = new ListItem()
{
Text = timeZone.DisplayName,
Value = timeZone.Id
};
ddlTimeZone.Items.Add(item);
}
}
Everything works fine but when I try to get the selected value I get an empty string
string item = ddlTimeZone.SelectedValue; -> empty string..
How can i solve this problem?
Because of the life cycle of controls in ASP.NET building a dynamic values will "disappear" in the PostBack process.
Try to call your initTimeZone method outside the if(!IsPostBack) condition and see if it works. like this:
protected void Page_Load(object sender,EventArgs e) {
if(!Page.IsPostBack) {
//Some Code
}
initTimeZone();
}
Check Control.EnableViewState for page or parent control. Maybe you turn it off?
I am trying to use two DropDownLists to filter data. I set both of the OnSelectedIndexChanged Equal to the method below. The problem is it is only grabbing the SelectedIndex of the DDL that is changed. Example: if i choose a option in DDL1 it grabs that value and doesnt grab the value of DDL2. They both have the same OnSelectedIndexChanged i figured it would grab the current value of both. Is there a way to make it look at both DDL Controls?
protected void BrandsList_SelectedIndexChanged(object sender, EventArgs e)
{
int DDLcatId = CategoriesList.SelectedIndex;
int DDLBraId = BrandsList.SelectedIndex;
IQueryable<Product> DDLprodResult = GetProductsDDL(DDLcatId, DDLBraId);
if(DDLprodResult == null)
{
}
else
{
CatLab.Text = DDLprodResult.ToList().Count().ToString();
productList.DataSource = DDLprodResult.ToList();
productList.DataBind();
}
}
Your code should work. Of course only one can be changed if you have set AutoPostBack="true"(default is false) on both. But you should get the correct SelectedIndex anyway in the handler.
So i will guess: you are databinding the DropDownLists on every postback. Do this only if(!IsPostBack), otherwise you always overwrite changes with the original values.
So for example in Page_Load:
protected void Page_Load(Object sender, EvengtArgs e)
{
if(!IsPostBack)
{
// DataBind your DropDownLists
}
}
protected void ddlEnvironment_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlEnvironment.SelectedIndex == 0)
{
ddlServers.Items.Add("item1");
}
if (ddlEnvironment.SelectedIndex == 1)
{
ddlServers.Items.Add("item2");
}
if (ddlEnvironment.Text == "Production")
{
}
}
The above is not working. When I make a selection on ddlEnvironment and it is the first item on the list (index 0), the other dropdownlist is not upading with "item1". Why?
There could be different reasons by default dropdown list do no do postback.
Check if you have AutoPostBack="true"
You bind the ddlEnvironment in !Page.IsPostBack block so that it maintains its state on postback
if(!Page.IsPostBack)
{
ddlEnvironment.AuutoPostBack = true;
ddlEnvironment.DataSource = datasource;
ddlEnvironment.DataBind();
}
I assume you have AutoPostBack=true - right?
If you're initializing ddlEnvironment in your Page_Load() event handler, it's being reset on postback.
You need to do something like this:
If (!Page.IsPostback)
{
// initialize ddlEnvironment here
}