Object reference not set to an instance of an object in ComboBox - c#

I've comboBox in windows forms which I've bound to datasource, which is correctly returning Id associated with particular name in combobox whenever form loads.
private void PurchaseMaster_Load(object sender, EventArgs e)
{
DataTable dt = productMasterBAL.GetTable("Select * from productMaster");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "ProductName";
combBox1.ValueMember = "ProductId";
}
But whenever I select any value in Combobox I get:
NullReferenceException was unhandled. Object reference not set to an
instance of an object
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView row = comboBox1.SelectedValue as DataRowView;
MessageBox.Show(String.Format("{0}", row["ProductId"])); //This line is causing exception
}
Could anyone please tell how can I solve this problem?

I think you should be checking combobox1.SelectedItem rather than SelectedValue.
DataRowView row = combobox1.SelectedItem as DataRowView;
SelectedItem is the databound row which created that entry in the combobox. SelectedValue will be the ProductID of that row.
Or, you could try
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string productId = combobox1.SelectedValue as string;
if (productId != null)
{
MessageBox.Show(productId);
}
}

You should be checking for the values like this
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
MessageBox.Show(cmb.SelectedValue.ToString());// cmb.SelectedText
}
This should give you the selected Product Id in the combobox
The items in Combobox are stored as ObjectCollection and not exactly a DataRow or DataRowView as you seem to be expecting.

Have you debugged? Check that row isn't null? from msdn:
The as operator is like a cast operation. However, if the conversion
is not possible, as returns null instead of raising an exception.
Have you checked if this expression is valid as type?

May be row["ProductId"] is not a string field I think, so its returning an exception while formatting.

You are trying to cast PName.SelectedValue which is of type "String" to object DataRowView\ using 'safe-cast'. as returns null if object can't be cast to desired class. So, the actual mistake is in
DataRowView row = PName.SelectedValue as DataRowView;
Try direct cast with DataRowView row = (DataRowView)PName.SelectedValue, you'll definitely will get an error.
You should query your data source again to fetch data object.

Check out my generic solution on this thread:
c# loop through combobox where datasource is a datatable with text
Basically, you can call my function, telling it the type of each ComboBox Item, and it'll do the rest.
ComboBoxHelper.SetComboBoxSelectionByValue<EmployeeRecord>(comboBoxEmployees, someEmployeeID);
Hope this helps!

Related

Add selected item from a bound listbox to a unbound listbox

i want to add selected item from a data bounded listbox (listbox1) to another listbox (listbox2)
Here is the code on a click event of a button.
private void btnrgt_Click(object sender, EventArgs e)
{
string x = listBox1.SelectedItem.ToString();
listBox2.Items.Add(x.ToString());
txttestno.Text = listBox2.Items.Count.ToString();
}
When i run this code System.data.datarowview get displayed in the listbox2.
Kindly help.
thank you in advance.
When you bind a ListBox datasource to a DataTable every item inside the ListBox is a DataRowView, not a simple string. In the ListBox you see a string displayed because you set the DisplayMember property of the ListBox with the name of a column in that DataRowView.
So, taking the current SelectedItem doesn't return a string but a DataRowView and calling ToString() for a DataRowView returns the full qualified name of the class (System.Data.DataRowView).
You need something like this
private void btnrgt_Click(object sender, EventArgs e)
{
DataRowView x = listBox1.SelectedItem as DataRowView;
if ( x != null)
{
listBox2.Items.Add(x["NameOfTheColumnDisplayed"].ToString());
txttestno.Text = listBox2.Items.Count.ToString();
}
}
EDIT
It is not clear what is the source of the error stated in your comment below, however you could try to avoid adding an item from the first listbox to the second one if that item exists in the second listbox with code like this
private void btnrgt_Click(object sender, EventArgs e)
{
DataRowView x = listBox1.SelectedItem as DataRowView;
if ( x != null)
{
string source = x"NameOfTheColumnDisplayed".ToString();
if(!listbox2.Items.Cast<string>().Any(x => x == source))
{
listbox2.Items.Add(source);
txttestno.Text = listBox2.Items.Count.ToString();
}
}
}
This solutions works if your second listbox is really populated adding simple strings to its Items collection.
On click button use below code.
protected void btnGo_Click(object sender,EventArgs e) {
string x = ListBox1.SelectedItem.Text;
ListBox2.Items.Add(x);
}

Dropdown List not returning the correct value

i am trying to retrieve the value on a previously databinded DropDownList like this:
<asp:DropDownList ID="DropDownListReception" runat="server" CssClass="span3 drop-down-reception"
OnPreRender="DropDownListReception_PreRender" OnSelectedIndexChanged="DropDownListReception_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
var receptions = BLLFactory.ReceptionBLL.GetListAll();
DropDownListReception.DataSource = receptions;
DropDownListReception.DataBind();
}
On the DropDown PreRender i am personalizing this DropDown like this:
protected void DropDownListReception_PreRender(object sender, EventArgs e)
{
if (DropDownListReception.DataSource != null)
{
DropDownListReception.Items.Clear();
DropDownListReception.Items.Add(new ListItem("-- Select --", "NA"));
foreach (Reception item in (DropDownListReception.DataSource as IEnumerable))
{
DropDownListReception.Items.Add(new ListItem(item.Name + " " + item.Number, item.Id.ToString()));
}
}
}
this is working perfectly, my DropDown loads as it should, my problem is when i try to retrieve the SelectedValue in the SelectedIndexChanged event, it wont return the value as a string but as a type, what i am doing is:
protected void DropDownListReception_SelectedIndexChanged(object sender, EventArgs e)
{
//CurrentReception is a string i want to save in ViewState
//I also tried (sender as DropDownList).SelectedValue
//Tried DropDownListReception.SelectedValue
CurrentReception = DropDownListReception.SelectedItem.Value;
}
but this "DropDownListReception.SelectedItem.Value" will always return "Reception" which is the type of the item, not the id i assigned as the item value in the PreRender event. This also happens if i do this: "DropDownListReception.SelectedItem.Text", this also return "Reception". How can i return the string Value i assigned to the DropDown item?
var CurrentReception = DropDownListReception.SelectedItem as Reception;
string val = CurrentReception.PropertyYouNeed;
DropDownListReception.SelectedItem.Text and DropDownListReception.SelectedItem.Value will return the value of the selection, which is the second term in the ListItem used when you add it to the list. In other words, the problem is with item.Id.ToString(). It returns the type of the object instead of the ID. I'm not sure what your item object actually consists of so I'm not sure what you actually need, but are you sure it's not just item.Id? ToString() is generally the string representation of the object, if item.Id is an int, then ToString should give you the string equivalent of that int... but the fact that it doesn't work suggests item.Id is not actually an int.
I think you need to cast the list item to the type that you stored in it (Reception), then access the property from the Reception object that you want (from your description it sounds like you want the id). Like this:
protected void DropDownListReception_SelectedIndexChanged(object sender, EventArgs e)
{
//CurrentReception is a string i want to save in ViewState
CurentReception = ((Reception)DropDownListReception.SelectedItem).Id.ToString();
}
I figured it out, i was DataBinding the DropDownList on the PageLoad, which fires before the SelectedIndexChanged event. Since the DropDown does a PostBack when its value changes, the PageLoad was "Recreating" the DropDown and i was losing the changes before getting to the SelectedIndexChanged code.
Thank you all for your answers.:)

Getting the value of a datagridview to a combobox. C#

The thing im trying to do is to get the value from a datagridview table already populated, to an editing phase, textbox are filling nicely but I cant find a way to assign the value of the table to a combobox item.
private void button2_Click(object sender, EventArgs e)
{
DataGridViewRow cliente = dataGridView1.CurrentRow;
textBoxDsClave.Text = cliente.Cells["dsClave"].Value.ToString();
textBoxDsRazonSocial.Text = cliente.Cells["dsRazonSocial"].Value.ToString();
comboBoxCnAceptaPromociones = cliente.Cells["cnAceptaPromociones"].Value.ToString(); //THIS ONE
}
Extra info, the data type of "cnAceptaPromociones" is bool, so it just has either "true" or "false".
I'm really new to C#, and i'm having a hard time learning.
Try setting the SelectedValue property:
comboBoxCnAceptaPromociones.SelectedValue =
Convert.ToBoolean(cliente.Cells["cnAceptaPromociones"].Value);

Get original object from DataRow in GridView C#

I try to display a collection (IEnumerable) of objects (generated via Linq to Sql). Therefore I bind the Gridviews DataSource property to the generated output of my Linq to SQL method. In the SelectedIndexChanged event of the GridView I try to convert the selected rows DataItem back to my original object but end up with a null value instead.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
RlDataContext dc = new RlDataContext();
this.dgvReports.DataSource = dc.GetReports(1);
this.dgvReports.DataBind();
}
protected void dgvReports_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.dgvReports.SelectedIndex >= 0)
{
Report rpt = (Report)this.dgvReports.SelectedRow.DataItem;
}
}
The return type of GetReports is ISingleResult<Report>
Use a bindingsource between your datagridview and your list. When a selection is made is datagridview use the bindingsource's Current property to get you the right item from the list.
This is how I always get my information from a datagridview
string variabel = yourDataGridView["Columnname"].ToString();
You can also use this in a loop then it will be:
string variabel = yourDataGridView["RowNumber"].Cells["Columnname"].Value.ToString();
I hope this helps!

Cannot cast DataItem to DataRowView in Custom Binding Scenario

I have an object that returns an IList which I'm getting from my ObjectDataSource and binding to a Gridview. All works fine if I just use standard binding, but I'm trying to customize my binding to set properties on a linkbutton as follows:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// extract the link button
LinkButton lnkViewMap = (LinkButton)e.Row.FindControl("lnkViewMap");
// grab the datarowview
System.Data.DataRowView row = (System.Data.DataRowView)e.Row.DataItem;
// set the onclientclick to fire our showMap javascript function,
// passing through the lat/longs
lnkViewMap.OnClientClick = string.Format("showMap({0}, {1}); return false;", row["Lat"], row["Long"]);
}
}
My error occurs where I am casting the e.Row.DataItem to a DataRowView. The code above is from Matt Berseth's awesome blog on Virtual Earth...which is what I am trying to implement here. Any ideas?
Set a breakpoint in the debugger and see what type e.Row.DataItem actually is.
It would only be a DataRowView if the DataSource you are setting on the grid is a DataView or DataTable. Otherwise it would be the element type of the collection.

Categories