kranthi4uonly
asked on
how to avoid adding duplicate items in listbox "C# windows forms"
i got a textbox and list box if i type some text in text box and click insert button it should add to list box but it should avoid ading duplicate items and it should also avoid adding blank space into list box
ASKER
it is wndows forms can u just give a sample code pelase it should check with the listbox as well as wit h the datasource please in my case it had dataset and datatables in it thank you
If the datatable has THAT field as a primary key, or you are free to change the primary key in the datatable, THIS works (assuming datatable bound to listbox with a single column):
private void button1_Click(object sender, EventArgs e)
{
string x = textBox1.Text;
if (x.Replace(" ", "") == "")
{
MessageBox.Show("need non-space text");
return;
}
DataTable dt = listBox1.DataSource as DataTable;
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
if (dt.Rows.Contains(x))
{
MessageBox.Show("no dups allowed:" + x);
return;
}
DataRow dr = dt.NewRow();
dr[0] = x;
dt.Rows.Add(dr);
}
If you can't change keys, you need to look for dups in a loop, like below instead:
string x = textBox1.Text;
if (x.Replace(" ", "") == "")
{
MessageBox.Show("need non-space text");
return;
}
DataTable dt = listBox1.DataSource as DataTable;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i][0].ToString() == x)
{
MessageBox.Show("no dups allowed:" + x);
return;
}
}
DataRow dr = dt.NewRow();
dr[0] = x;
dt.Rows.Add(dr);
private void button1_Click(object sender, EventArgs e)
{
string x = textBox1.Text;
if (x.Replace(" ", "") == "")
{
MessageBox.Show("need non-space text");
return;
}
DataTable dt = listBox1.DataSource as DataTable;
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
if (dt.Rows.Contains(x))
{
MessageBox.Show("no dups allowed:" + x);
return;
}
DataRow dr = dt.NewRow();
dr[0] = x;
dt.Rows.Add(dr);
}
If you can't change keys, you need to look for dups in a loop, like below instead:
string x = textBox1.Text;
if (x.Replace(" ", "") == "")
{
MessageBox.Show("need non-space text");
return;
}
DataTable dt = listBox1.DataSource as DataTable;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i][0].ToString() == x)
{
MessageBox.Show("no dups allowed:" + x);
return;
}
}
DataRow dr = dt.NewRow();
dr[0] = x;
dt.Rows.Add(dr);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
In either case, the insert button can check the values of the text box for blank space and duplicates (by checking against the data source) before doing the insert.