ComboBox SelectedItem from DataTable Winforms C#? - c#

I have a method in my DAL which populates a ComboBox from a DataTable. ComboBox displays correctly and I have a 'Save' button which saves back to my DB, job's a good'un...
public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("#id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetName(#id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch
{
MessageBox.Show("Unable to populate Name LookUp");
}
Combo.DataSource = dt;
Combo.DisplayMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
{
Combo.SelectedItem = dr["company_int_name"].ToString();
}
}
return "";
}
However obviously when I re-edit the record, this method is called again. Ok, I now have written a ForEach loop which iterates over my DataTable and compares the string in the rows to the Name I am passing in. If the two match I'm setting the
Combo.SeletedItem = dr["company_int_name"].ToString();
However the selectedItem is not being set, presumably I'll need some sort of event to notify the property changed?
Thanks

You have to bind the Combo Box with the ValueMember function and can reflect the combo box with the matched string value as selected
public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("#id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetName(#id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch
{
MessageBox.Show("Unable to populate Name LookUp");
}
Combo.DataSource = dt;
Combo.DisplayMember = "name";
Combo.ValueMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
{
Combo.SelectedValue = dr["company_int_name"].ToString();
}
}
return "";
}

Related

I have a problem with link datagridview and custome database column

private void Purchases_Load(object sender, EventArgs e)
{
com.Connection = con;
con.Open();
com.CommandText = "select * from Items";
com.ExecuteNonQuery();
DataTable dt7 = new DataTable();
SqlDataAdapter da7 = new SqlDataAdapter(com);
da7.Fill(dt7);
ComboColumn.DataSource = dt7;
ComboColumn.DisplayMember = "Name";
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
com.Connection = con;
com.CommandText = "select ID from Items where Name = '" + ComboColumn + "' ";
con.Open();
com.ExecuteNonQuery();
SqlDataReader dr;
dr = com.ExecuteReader();
while (dr.Read())
{
string id = (string)dr["ID"].ToString();
}
con.Close();
}
I have sql db table contains ID and Items.
also, I have winform and I'm using DataGrid type "DataGridViewComboBoxColumn" to select the items from db table and it's working perfectly
now, The problem is I need to show the following "ID column" to the second column in DGV while I selecting the items from "DataGridViewComboBoxColumn".
So, I need help to link a specific column in database which is (ID) with a specific column on datagrid column type "DataGridViewTextBoxColumn" when user select items from the gdv ComboBoxColumn.
note: 1st scop of code working and giving me items from db.
2nd scop of code not working and I can't handle it for retrieve ID from db table!!
The answer is here!
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewComboBoxCell comboBoxCell = (row.Cells[2] as DataGridViewComboBoxCell);
comboBoxCell.Items.Add("Select Goods");
comboBoxCell.Value = "Select Goods";
DataTable dt_1 = this.GetData("SELECT ID,Name from Goods");
foreach (DataRow drow in dt_1.Rows)
{
string customerId = drow[0].ToString();
comboBoxCell.Items.Add(drow[0] + "-" + drow[1]);
if (customerId != "3")
{
if (row.Cells[2].Value.ToString() == customerId)
{
comboBoxCell.Value = drow[1];
}
}
}

combobox value not showing in C#

I get problem while loading Combobox value from database. I am using SQLite Database. It only show a single value in Combobox but in my database there is multiple value. So how can i do this.
This is my Code:
Class DatabaseHandler it has two methods which Execute Query and other methods return DataTable object:-
public int ExecuteSql(String Query)
{
SQLiteCommand command = new SQLiteCommand(Query, Connection);
return command.ExecuteNonQuery();
}
public DataTable GetDataTable(String Query)
{
SQLiteCommand command = new SQLiteCommand(Query, Connection);
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
This is Category Class and this is piece of code where i got a problem:-
private void CategoryName()
{
try
{
String Query = "Select CategoryName from CategoryTable;";
databaseHandler.ExecuteSql(Query);
DataTable dataTable = databaseHandler.GetDataTable(Query);
ProductType.DataSource = dataTable;
ProductType.DisplayMember = "CategoryName";
}
catch (Exception CatID)
{
Console.WriteLine(CatID.StackTrace);
}
}
I think you are assigning a DisplayMember but not ValueMember. Please assign the DisplayValue along with ValueMember.
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

How do you get the Id of the item in CheckListBox

I have a checkListBox in my windows form application and binded with my database data with SQL. I populate a list of item according to what I select from my comboBox. If I select item 1 from my comboBox, it will display customers' name who is using this item. I want get customers' id according to what I check in my checkListBox.
Here is how I fill my comboBox
private void fill_comboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
string query = "select itemId, itemName from item_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select an item-------> " };
dt.Rows.InsertAt(dr, 0);
itemComboBox.DataSource = dr;
itemComboBox.ValueMember = "itemId";
itemComboBox.DisplayMember = "itemName";
fill_customerCheckListBox();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is how I fill my checkListBox
private void fill_customerCheckListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
DataSet myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
string commandString = "select fullName from[customer_detail] as cd LEFT JOIN[item_customer] as ic ON ic.customerId= cd.customerI WHERE ic.itemId= '" + itemCombBox.SelectedValue + "' ";
myCommand = new SqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = commandString;
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataAdapter.TableMappings.Add("Table", "customer_detail");
myDataAdapter.Fill(myDataSet);
DataTable myDataTable = myDataSet.Tables[0];
customerCB.Items.Clear();
string s = "Select All Customer";
customer.Items.Add(s);
foreach (DataRow dataRow in myDataTable.Rows)
{
customerCB.Items.Add(dataRow["fullName"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a praremter for loop that trying to loop through every checked item from my customerCB, but this isn't working. When I am in my debug mode, the code DataRow row = (itemChecked as DataRowView).Row; is causing an exception
Object reference is not set to an instance of an object.
I have no idea how to fix this. Help will be appreciated, thanks
string parameterList = "";
foreach (object itemChecked in customerCB.CheckedItems)
{
DataRow row = (itemChecked as DataRowView).Row;
parameterList += (parameterList.Length == 0) ? row[0].ToString() : ", " + row[0].ToString();
}
Try the Following way !!
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string fullName= castedItem["fullName"];
}
(OR) You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (itemChecked as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("fullName");
}
it seems than when you are populating your combobox your are entering dataRow["fullName"] therefore this cast DataRow row = (itemChecked as DataRowView).Row won't work as itemChecked only contains the value of fullName and not the row, try adding the dataRow instead.

Bind a returned object of DropDownList to an asp:DropDownList webform

To help reuse some code, I wanted to generate DropDownList objects and assign those to the web form fields in ASP.NET C#.
I can't seem to bind my object (DropDownList) to my webform. Is this proper way to do it? Is there a better way? I know I'll use this dropdown and many like it on other web forms. And I wanted to place all these in one class that I can call.
Here is my method to return the dropdown object.
protected DropDownList ddNames() {
DropDownList dd = new DropDownList();
dd.Items.Clear();
string selectSQL = "mysql stuff";
string connString = "my string";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
SqlDataReader reader;
try {
conn.Open();
ListItem newItem;
reader = cmd.ExecuteReader();
while ( reader.Read() ) {
newItem = new ListItem();
newItem.Text = DataHelpers.GetUserFirstLastFromID(Convert.ToInt32(reader["someid"]));
newItem.Value = reader["someid"].ToString();
dd.Items.Add(newItem);
}
reader.Close();
newItem = new ListItem();
newItem.Text = "Unassigned";
newItem.Value = "999999";
dd.Items.Add(newItem);
} catch (Exception ex) {
throw ex;
} finally {
if (conn != null) {
conn.Dispose();
conn.Close();
}
}
return dd;
}
And on my webform its a simple
<asp:DropDownList ID="dd_name" runat="server"></asp:DropDownList>
Then when in my codebehind, I tried to call something similar but it doesn't work:
dd_name.DataSource = ddNames();
I also tried Bind and other stuff.
Is this possible? Is there a better way?
I have adjusted your code for you to be able to bind your data to your dropdownlist
protected ICollection ddNames() {
string selectSQL = "mysql stuff";
string connString = "my string";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
SqlDataReader reader;
// Create a table to store data for the DropDownList control.
DataTable dt = new DataTable();
// Define the columns of the table.
dt.Columns.Add(new DataColumn("NewItemTextField", typeof(String)));
dt.Columns.Add(new DataColumn("NewItemValueField", typeof(String)));
dt.Rows.Add(CreateRow("Unassigned", "999999", dt));
try {
conn.Open();
reader = cmd.ExecuteReader();
while ( reader.Read() ) {
// Populate the table with sample values.
dt.Rows.Add(CreateRow(DataHelpers.GetUserFirstLastFromID(Convert.ToInt32(reader["someid"])), reader["someid"].ToString(), dt));
}
reader.Close();
} catch (Exception ex) {
throw ex;
} finally {
if (conn != null) {
conn.Dispose();
conn.Close();
}
}
return dt;
}
DataRow CreateRow(String Text, String Value, DataTable dt)
{
// Create a DataRow using the DataTable defined in the
// CreateDataSource method.
DataRow dr = dt.NewRow();
// This DataRow contains the NewItemTextField and NewItemValueField
// fields, as defined in the CreateDataSource method. Set the
// fields with the appropriate value. Remember that column 0
// is defined as NewItemTextField, and column 1 is defined as
// NewItemValueField.
dr[0] = Text;
dr[1] = Value;
return dr;
}
Then finally your call to the method and bindings to the dropdownlist would be:
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
dd_name.DataSource = ddNames();
dd_name.DataTextField = "NewItemTextField";
dd_name.DataValueField = "NewItemValueField";
// Bind the data to the control.
dd_name.DataBind();
// Set the default selected item, if desired.
dd_name.SelectedIndex = 0;
Inspired by DropDownList Class

How to show all the rows in datagridview?

DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;

Categories