Hie friends
Well i used a button and combo box . when i click on button it should display what ever i selected in combo box :) when i select something in comboBox its working fine but when i un-intentionally click on button without selecting anything in comboBox ITS THROWING me Null Reference Exception :(
How to handle this ? Is there any other way except exceptional handling ?
My Code :
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(comboBox1.SelectedItem.ToString());
}
(OR)
private void button1_Click(object sender, EventArgs e)
{
foreach(object obj in ComboBox1.SelectedItem.ToString())
MessageBox.Show(obj.ToString());
}
Foreach also failed to handle null but its not used here in this context :D
Thank you in advance
Loading

Upamanyu Roy ChoudhuryPosted Feb 21, 2013, 4:11 AM
The SelectedItem property of Combobox is NULL when we do not select any item from the ComboBox, so when we try to write
MessageBox.Show(comboBox1.SelectedItem.ToString());It will throw an exception.
Therefore you need to put a checking to bypasss this error
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1)
{
MessageBox.Show(comboBox1.SelectedItem.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("India");
comboBox1.Items.Add("Pakistan");
comboBox1.Items.Add("Bangladesh");
}
I hope it is now clear to you, please mark this post as an answer if it is of any help
SUNIL GUTTAPosted Feb 21, 2013, 1:05 PM
Thank you thank you once again :)
if (comboBox1.SelectedIndex != -1)
It is just perfect :) i also came across it but i ended up at
if (comboBox1.SelectedIndex = -1) :) ha ha
Thank you
and
Satyapriya Nayak Humm when i tried your case problem still do exists :) ty for ur quick reply ty just fallow-up above solution by Upamanyu Roy Choudhury its just perfect :)
Satyapriya NayakPosted Feb 21, 2013, 4:13 AM
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Combobox is not Selected.");
}
else
{
MessageBox.Show(comboBox1.SelectedItem.ToString());
}
}
private void Form2_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("a");
comboBox1.Items.Add("b");
comboBox1.Items.Add("c");
}
}
}