First combobox item missing after combobox filled with datatable - c#

I have a combobox on my form and a datatable. The combobox will be filled by some row values fro the datatable. But before that I would like to add a combobox item called (new) that will be the first option of the combobox in case the user would like to add a new item.
But when my combobox is filled, my (new) does not show up for some reason.
string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);
comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
comboSMSMessages.Items.Clear();
for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
{
ComboboxItem item = new ComboboxItem()
{
Text = dtSmsMessages.Rows[i]["Name"].ToString(),
Value = dtSmsMessages.Rows[i]["Id"].ToString()
};
comboSMSMessages.Items.Add(item);
}
}
comboSMSMessages.SelectedIndex = 0;

comboSMSMessages.Items.Clear(); Clear all the items
Add comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
after you cleared the combobox Your code should be like
string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);
if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
comboSMSMessages.Items.Clear();
comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
{
ComboboxItem item = new ComboboxItem()
{
Text = dtSmsMessages.Rows[i]["Name"].ToString(),
Value = dtSmsMessages.Rows[i]["Id"].ToString()
};
comboSMSMessages.Items.Add(item);
}
}
comboSMSMessages.SelectedIndex = -1;

Related

Using dt.select to populate dropdown

I'm trying to populate a dropdown with selectedvalues from my database. The reason why I'm using a dt.select is because I don't want to keep calling the stored procedure for every dropdown (I have about 20 dropdowns).
The problem is if there is a value London in Location dropdown and London in Department dropdown, it'll populate in both dropdown. I only want it to populate in Location or in Department. I have a feeling that it could be this part in my code that populating both ddl.
if (ddlLocation.Items[j].Value.ToString() == ds.Tables[0].Rows[i][0].ToString())
I would like to go through the data row and only populate those values.
DataTable dt = new DataTable();
DataSet ds = obj.runSPHere(GUID);
dt = ds.Tables[0];
//Populate the Location Dropdown
DataRow[] Location = dt.Select("Category = 'Location'");
foreach (DataRow row in Location)
{
for (int i = 0; ds.Tables[0].Rows.Count > i; i++)
{
for (int j = 0; ddlLocation.Items.Count > j; j++)
{
if (ddlLocation.Items[j].Value.ToString() == ds.Tables[0].Rows[i][0].ToString())
{
ddlLocation.Items[j].Selected = true;
}
}
}
}
//Populate the Department Dropdown
DataRow[] Department = dt.Select("Category = 'Department'");
foreach (DataRow row in Department)
{
for (int i = 0; ds.Tables[0].Rows.Count > i; i++)
{
for (int j = 0; ddlDepartment.Items.Count > j; j++)
{
if (ddlDepartment.Items[j].Value.ToString() == ds.Tables[0].Rows[i][0].ToString())
{
ddlDepartment.Items[j].Selected = true;
}
}
}
}
Here's how I did it.
Start with a stored procedure that gets the id column and the actual column that you want populating your dropdowns. You'll want a separate SELECT statement for each dropdown:
SELECT id, location
FROM LocationTable
SELECT id, department
FROM DepartmentTable
Then create a method for populating your dropdowns:
private void PopulateDropdowns()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["name of your connection string"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "name of your stored procedure";
// Double check that the connection is open
if (conn.State == ConnectionState.Closed)
conn.Open();
// Create a SqlDataAdapter and fill it with the data from your stored procedure
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
// Since you have so many, I would name the DataSet tables
// These will correspond with each of your SELECT statements
// with 0 being the first SELECT, 1 being the second SELECT and so on
ds.Tables[0].TableName = "Location";
ds.Tables[1].TableName = "Department";
// Then set their DataSources
// and bind each table to its corresponding dropdown
ddlLocation.DataSource = ds.Tables["Location"];
ddlLocation.DataValueField = "id";
ddlLocation.DataTextField = "location";
ddlLocation.DataBind();
ddlDepartment.DataSource = ds.Tables["Department"];
ddlDepartment.DataValueField = "id";
ddlDepartment.DataTextField = "department";
ddlDepartment.DataBind();
}
}
}
And if you'd like the default option in your drop down to say something other than whatever comes first from your SELECT statements, you can set a property called AppendDataBoundItems to true. Then manually add a ListItem to your drop down, set its Text to whatever you like and set its Value to -1 (to get it to float to the top):
<asp:DropDownList runat="server" ID="ddlLocation" AppendDataBoundItems="true">
<asp:ListItem Enabled="true" Text="Please Select" Value="-1"></asp:ListItem>
</asp:DropDownList>
Then I put PopulateDropdowns(); in my page load. It runs the stored procedure once and all the dropdowns on the page are populated.
You can use DataView to separate your results like this way :
var locationView = new DataView(dt)
{
RowFilter = "Category = 'Location'"
};
foreach (DataRowView rowView in locationView)
{
DataRow row = rowView.Row;
for (int j = 0; ddlLocation.Items.Count > j; j++)
{
if (ddlLocation.Items[j].Value.ToString() == row[0].ToString())
{
ddlLocation.Items[j].Selected = true;
}
}
}
so you can create two views one for location and another for department one time and use them whenever you need them.
I noticed that you're looping in your filtered rows then inside it looping through all your table rows. and I think this is what makes your code not functioning as you wish. I hope I helped you

how to display the datavaluefield of selected items in different listbox in asp.net

I have 3 listboxes.The listbox fetches two values by code-datatextfield and datavaluefield. 1st listbox transfers the datatextfield items from 1st listbox to 2nd listbox.i want to transfer the datavaluefield of selected 1st listbox items to 3rd listbox.
if (ListBox3.SelectedIndex >= 0
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
Session["value"] = ListBox3.Items[i];
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}
for listbox 3
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where pname='" + this.DropDownList1.SelectedValue + "'" ,con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox3.DataSource = ds.Tables[0];
ListBox3.DataTextField = "paramtext";
ListBox3.DataValueField = "param";
ListBox3.DataBind();
}
}
But i want to display the datavaluefield of the items that are selected from listbox3 to listbox1
Since you want to show DataTextField value and DataValueField value from one listbox into 2 different listbox. I suggest you to use a different approach. This will also reduce usage of 2nd database call.
Try following:-
if (ListBox3.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
//Session["value"] = ListBox3.Items[i]; no need of this
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (ListBox2.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
//since you already have text and value field values in arrayList. Use them
ListBox2.Items.Add(new ListItem(((ListItem)arraylist1[i]).Text));
}
if (ListBox1.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
ListBox1.Items.Add(new ListItem((ListItem)arraylist1[i]).Value));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
/* This database call can be removed
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}*/

Why do i get System.Data.DataRow?

I wanna show my rows in a listbox and the table names but when i run my code it says System.Data.DataRow can someone help me
my code is
foreach (object SelectedValue in ListEmployees.SelectedItems)
{
using (connection = new SqlConnection(connectionstring))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM " + selectedCel, connection))
{
DataTable employees = new DataTable();
adapter.Fill(employees);
for (int i = 0; i < employees.Rows.Count; i++)
{
DataRow dr = employees.Rows[i];
ListViewItem itm = ListViewItem(dr.ToString());
listView1.Items.Add(itm);
}
}
}
DataRow.ToString() just prints out the full type name.
Presuming you want to show the first column:
ListViewItem itm = new ListViewItem(dr.Field<string>(0));
i wanna show all columns that are in the table
string[] allColumns = dr.ItemArray.Select(obj => obj.ToString()).ToArray();
ListViewItem itm = new ListViewItem(allColumns);

not able to set default value in combobox : C#

I was trying to add a default value ("--select item--") in existing ComboBox which is getting filled by Database table. Here is my code.
SqlConnection conn = new SqlConnection("Server = .\\SQLEXPRESS; Initial Catalog= Student; Trusted_Connection = True");
string query = "select Id, Name from abc1";
SqlDataAdapter da = new SqlDataAdapter();
conn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
comboBox1.DataSource = dt;
comboBox1.ValueMember = "Id";
comboBox1.DisplayMember = "Name";
Everything is working fine in above code and I'm getting CB filled with desired values.
Now when I try to insert default value using below, then it is throwing an error. This way was tried here
comboBox1.Items.Insert(0, "Select"); //this is throwing an error
comboBox1.SelectedIndex = 0;
I further explored below code to add default item.
comboBox1.SelectedIndex = -1;
comboBox1.Text = "Select an item";
This added an item as desired, but on any event, CB loses this value. After SelectIndexChanged event, I lose this value. So this cannot be my solution.
Any advise?
I'd rather not intefere into binding, but edit SQL instead:
string query =
#"select 0 as Id, -- or whatever default value you want
'select' as Name,
0,
union all
-- your original query here
select Id,
Name,
1
from abc1
-- to have default value on the top
order by 3 asc";
Insert's second parameter is expecting a ComboBox.ObjectCollection object.
Try doing this:
Having a class
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
}
And using:
// This could be inline, but for simplicity step by step...
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
//or
comboBox1.Items.Insert(0, item);
You can add programmatically the item to the datatable
DataRow dr = dt.NewRow();
dr["id"] = "0";
dr["name"] = "Select";
dt.Rows.InsertAt(dr, 0);
then you can set the datasource
comboBox1.DataSource = dt;
If you just want to show a suggestion text to your user, the "EDIT" part of this answer may help (can only work if your ComboBox's DropDownStyle is not set to DropDownList).
But if you really want some "Select" item in your ComboBox, try this:
void Form1_Load(object sender, EventArgs e)
{
//load your datatable here
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
comboBox1.Items.Add(new { ID = 0, Name = "Select" });
foreach (DataRow a in dt.Rows)
comboBox1.Items.Add(new { ID = a["ID"], Name = a["Name"] });
comboBox1.SelectedIndex = 0;
comboBox1.DropDown += new EventHandler(comboBox1_DropDown);
comboBox1.DropDownClosed += new EventHandler(comboBox1_DropDownClosed);
}
void comboBox1_DropDownClosed(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
{
comboBox1.Items.Insert(0, new { ID = 0, Name = "Select" });
comboBox1.SelectedIndex = 0;
}
}
void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
comboBox1.Items.Remove(new { ID = 0, Name = "Select" });
}

How to get value member of checked items in checkedlistbox windows control?

am using the following code to bind a checkedlistbox in win form.I want to get the value member of of checked items in checkedlistbox ?
listCollection = new List<ListItem>();
listCollection.Add(new ListItem { text = "Manufacturer", value = "1" });
listCollection.Add(new ListItem { text = "Dealer", value = "2" });
listCollection.Add(new ListItem { text = "Distributor", value = "3" });
listCollection.Add(new ListItem { text = "Trader", value = "4" });
listCollection.Add(new ListItem { text = "Service Provider", value = "5" });
chkListCategory.DataSource = listCollection;
chkListCategory.DisplayMember = "text";
chkListCategory.ValueMember = "value";
I don't know what is ListItem but I suppose it is a class that is looks like:
public class ListItem
{
public string Text;
public object Value;
public ListItem(string text, object value)
{ /*...*/ }
}
So, change the DisplayMember = "text"; to "Text" and ValueMember = "value"; to "Value":
chkListCategory.DisplayMember = "Text";//"text";
chkListCategory.ValueMember = "Value";//"value";
The display text at UI will be "Manufacturer, Dealer, Distributor, ..."
And the values will be "1, 2, 3, ..."
Get the value member of checked items:
To get the values of checked items:
//first checked item.
var value = (chkListCategory.CheckedItems[0] as ListItem).Value;
//all checked items.
foreach (var value in chkListCategory.CheckedItems)
{
Console.WriteLine((value as ListItem).Value);
}
//value at any index in the chkListCategory:
var value = (chkListCategory.Item[index] as ListItem).Value;
Bind CheckedListBOx or any other control with displaymember and valuemember is quite simple you just need to specify datasource property of control as well as displaymember and valuemember.
Following is working code 100 % work for me i have tested:
/* checkedlistbox bindig code */
DataSet ds = new DataSet();
string strChechboxlist = "select Subject_ID as code, SubjectName as Display from dbo.Mst_Subject_Detail";
/* filldataset() is function i have created to return dataset. */
ds = dc.FillDataSet(strChechboxlist);
if (ds.Tables[0].Rows.Count > 0)
{
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DisplayMember = "Display";
checkedListBox1.ValueMember = "code";
}
/* for fetching valuemember or displaymember from checkedlistbox */
for(int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
/*Now with the following code we can get valemember and displaymember as per your requirement you can store in table. */
DataRow r;
r = ((DataRowView)this.checkedListBox1.CheckedItems[i]).Row;
string val = (r[this.checkedListBox1.ValueMember]).ToString();
string dis = (r[this.checkedListBox1.DisplayMember]).ToString();
r = null;
}
Note :- I am attaching working demo of code
Here is the code to get some records from Database and put these in a CheckedListBox
SqlCommand cmd = new SqlCommand(#"SELECT Code, GenericName FROM tbl_Item", Connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
chklItems.DataSource = null; // chklItems is a CheckedListBox
if (chklItems.Items.Count > 0)
chklItems.Items.Clear();
chklItems.DataSource = dt;
chklItems.DisplayMember = "GenericName";
chklItems.ValueMember = "Code";
To Get value member of checked items
for (int i = 0; i < chklItems.CheckedItems.Count; i++)
{
string code = ((DataRowView)chklItems.CheckedItems[i]).Row["Code"].ToString();
}
foreach(DataRowView view in chkListCategory.CheckedItems)
{
Console.WriteLine(view[chkListCategory.ValueMember].ToString());
}

Categories

Resources