Bad enum field value in asp.net - c#

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

Related

how to set Check Repository radio group in gridcontrol devexpress using C# from value another table

i have repository radio group in grid control cell, i wanna set checked in repository radio while value from another cell. this my sample:
while ISJAWAB value is 1, repository radio group will be checked in column PILIH.
i have tried simple code but it doesn't work:
private void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column.FieldName == "PILIH")
{
var val = Convert.ToString(gridView2.GetRowCellValue(e.RowHandle, "ISJAWAB"));
if (val == "1")
{
e.DisplayText = "1"; //nilai 1 untuk select radio
}
}
}
in the repository collection i have set value to 1, and it automatically set check in repository radio group.
need help ??
RadioGroup is not the best choice for the in-place editor in this case, as it gives you redundant functionality to display several choices within single cell. For your purpose you can use CheckEdit. Also, with CustomDrawCell event you will have to actually manually redraw your radio buttons. There's an easier solution utilizing unbound columns.
So I suggest the following solution:
1.Add CheckEdit repository item, set it's CheckStyle property equal to Radio.
2.Make your PILIH column's Unbound Type = Boolean. Assign above mentioned CheckEdit repository item to it's ColumnEdit. Set OptionsColumn.AllowEdit = false.
3.Add gridView2.CustomUnboundColumnData event handler with body like following:
private void gridView2_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.IsGetData && e.Column.FieldName == "PILIH")
{
var row = (DataRow) e.Row;
var val = Convert.ToString(row["ISJAWAB"]));
if (val == "1")
{
e.Value = true;
}
}
}
you must change the type of reposityRadio to Boolean to true instead of 1 :
2nd the PILIH column data source must be type bool
and use this code :
private void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column.FieldName == "PILIH")
{
var val = Convert.ToString(gridView2.GetRowCellValue(e.RowHandle, "ISJAWAB"));
if (val == "1")
{
gridView2.SetRowCellValue(e.RowHandle, "PILIH", true);
}
}
}
the result should be like this :

RadioButtonList null values

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.

How do I Grab Selected Index on two Dropdownlist's OnSelectedIndexChanged?

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

Unable to delete data from database

I encountered a problem whereby when the user clicked on the delete button, Nothing happens and when I insert breakpoint to check, The selectLocStation is null. Why is it happening? Can anyone kindly solve my doubts about it?
Here are the codes for you to see my Delete codes. Appreciate any helps that were offered.
private void btnDel_Click(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue);
var DeleteRTiming =
(from delLocStation in Setupctx.requiredtimings
where delLocStation.RequiredLocationStationID == selectLocStation
select delLocStation).SingleOrDefault();
if (DeleteRTiming != null)
{
Setupctx.DeleteObject(DeleteRTiming);
Setupctx.SaveChanges();
cbLocStation.SelectedIndex = -1;
this.Edit_TS_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Required Timing And " +
"The Location Station Has Been Deleted.");
}
}
}
This is the codes that were used to bind.
private void Edit_TS_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var DeleteRT = (from DelRT in Setupctx.requiredtimings
join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID
select ls.locStatname).Distinct().ToList();
foreach (var locstationData in DeleteRT)
{
cbLocStation.Items.Add(locstationData);
}
}
}
How can selectLocStation be null ? it is of type int, are you getting any exception or you mean your object DeleteRTiming is null ? probably its the DeleteRTiming which is null
The simple answer to that the record you are looking in the database against selectLocStation is not there.
You need to put a break point and see what is being held by 'selectLocStation` and then check the database manually if the record exists in the database.
when you bind your control, you must set it in ! IsPostback and persist you with ViewState
If(! IsPostBack)
{
BindYourControl(); //For just first load.
}
Persist with
EnableViewState = true;
In order to don't erase your selected value
If this is a silverlight application then you might want to use
cbLocStation.SelectedItem
Or it is a ASP.Net site and you rebind the data on every pageLoad
Either way you should have an exception because you are trying to convert a null value.
See the method that you have used to bind the combo box
cbLocStation.Items.Add(locstationData);
This will create the combobox with "ValueField" and "TextFiled" with value of the variable "locstationData"
So when you try to get selected value from cbLocStation.SelectedValue ,it will always contain name and so you cannot parse it to integer.
There is another overload for the "Add" Which will accept Value(Id) and Text(Text to display)
cbLocStation.Items.Add(new ListItem(locstationData.locStatname, locstationData.locStatID));
Try to change the binding portion like this

Comboboxes only load when selecting the second items and below

This is really strange. I want to select a State and load Cities from that State in another combobox.
It's working EXCEPT when selecting the first item in the combobox:
Here's my entire class. The if statement in the selectedIndexChanged is to make sure that something is selected. The problem is that if I set that to cmbState.SelectedIndex >= 0 then an exception is raised because on initial load the comboBox doesn't has a .State variable there and not a .Value.
I don't know if this makes any sense.
private void MainForm_Load(object sender, EventArgs e)
{
LoadDepartmentsToComboBox();
}
private void LoadCitiesToComboBox(long StateID)
{
cmbCity.DataSource = null;
CityRepository cityRepo = new CityRepository();
cmbCity.DataSource = cityRepo.FindAllCities().Where(c => c.IDState == StateID);
cmbCity.DisplayMember = "Name";
cmbCity.ValueMember = "ID";
}
private void LoadDepartmentsToComboBox()
{
cmbState.DataSource = null;
StateRepository stateRepo = new StateRepository();
cmbState.DataSource = stateRepo.FindAllStates();
cmbState.DisplayMember = "Name";
cmbState.ValueMember = "ID";
}
private void cmbState_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbState.SelectedIndex > 0)
{
LoadCitiesToComboBox(Convert.ToInt64(cmbState.SelectedValue));
}
}
If I do use cmbState.SelectedIndex >= 0 then I receive this exception:
Unable to cast object of type
'DocumentScannerDanyly.State' to type
'System.IConvertible'.'System.IConvertible'.
When I don't use the SelectedIndex >= 0 and use plain old >0 then everything works except when selected the first item, which does nothing; understandably because it doesn't take the first item into account.
Thanks a lot for the help.
Don't assign the Display member & the Value member in each load, just assign them once in constructor for example.
add ToList() to the result which will assign to DataSource,
Complex DataBinding accepts as a data source either an IList or an IListSource.
check this.

Categories

Resources