bind data on dropdownlist - c#

I'm trying run this code
private void LoadProdName()
{
con.Open();
cmd = new SqlCommand(#"SELECT productName
FROM Products3
WHERE productType = #Type",con);
cmd.Parameters.AddWithValue("#Type",ddlProducts.SelectedItem.Value.ToString());
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
ddlProdName.DataSource = dt;
ddlProdName.DataBind();
con.Close();
}
my selectedIndesChange codes:
protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
{
LoadProdName();
}
which uses the value of my first dropdownlist.My problem is whenever I select a ProductType on my dropdownlist it will fill my second DDL with the select query but I am not getting any data at all from my second dropdownlist.
Now I'm getting some progress.
This is what I get now:

For cascade drowdownlist you must do a postback in your dropdownlist event "OnSelectedIndexChanged" or use an AJAX call to your method
try this guide: http://www.aspsnippets.com/Articles/Creating-Cascading-DropDownLists-in-ASP.Net.aspx
try this code after your query
ddlProdName.DataSource = cmd.ExecuteReader();
ddlProdName.DataTextField = "productName";
ddlProdName.DataValueField = "productName"; //or productId
ddlProdName.DataBind();

In your case, you will want to do:
ddlProdName.DataTextField = "productName"; //this is the name of column that's in your datatable.
ddlProdName.DataValueField = "productName";
If you are specifying anything other than collection of simple data type as the data source, you will need to specify the DisplayMember and ValueMember (in winforms) and DataTextField and DataValueField (in webforms, from Sergio's answer) property of the combobox so that it knows which property to display and which should be used as value.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
DataColumn prodName = new DataColumn("Products");
dt.Columns.Add(prodName);
dt.Rows.Add("a");
dt.Rows.Add("b");
dt.Rows.Add("c");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Products";
comboBox1.ValueMember = "Products";
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Related

Insert data in comboBox from database

I want to add all Id from customer table in combobox using class and this is my connection class connectionClass in which I made a function for selecting data from databse.
The second is my Customer form(this is customer form coding customerForm) in which i call a function which i made in connection class .
but it only showing the last id in customer form and i want all id in combobox
In the select() method you are returning a string,instead of that you need to populate
dataset and bind the data to combobox.
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("customerid", typeof(string));
dt.Columns.Add("contactname", typeof(string));
dt.Load(reader);
regards
chandra
Instead of string return a List of strings as follows:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Fill_Combo();
}
public void Fill_Combo()
{
Connection2DB cst = new Connection2DB();
cmbBoxId.Items.AddRange(cst.Select().ToArray());
}
}
class Connection2DB
{
public List<string> Select()
{
var ids = new List<string>();
try
{
string sqlqry = "select ID from Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con);
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
ids.Add(dr["ID"].ToString());
}
}
catch (Exception ex)
{
// Handle exception here
}
return ids;
}
}
this function only returning only ID from Customer table. I want to multiple data from Customer table using same method. Can you help me in this one??
Normally, this is not how this site works. First, you should ask a specific question, and show what you have done. Then we may help you.
Here I will try to give you two general solutions for working with a database.
Solution 1:
Let`s say you want to display everything retrieved from the database to your windows form.
First, create the DataGridView object let's call it dataGridView1. You can create it using the designer as any other control. then use the codes below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = GetData();
}
public DataTable GetData()
{
string ConStr = " your connection string "; // Write here your connection string
string query = #"SELECT * FROM Customer"; // or write your specific query
DataTable dataTable = new DataTable();
SqlConnection conn = new SqlConnection(ConStr);
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = null;
try
{
conn.Open();
// create data adapter
da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show($"Cannot read database: {ex.Message}");
}
finally
{
conn.Close();
if (da != null)
da.Dispose();
}
return dataTable;
}
public void FillDataGrid()
{
Connection2DB cst = new Connection2DB();
dataGridView1.DataSource = cst.GetData();
}
}
Solution 2:
Let's say from your database table you want to extract 3 columns: ID (INT), Name (VARCHAR(100)) and Value (VARCHAR(MAX).
First, create a class:
public class Customer
{
public int ID { get; set; }
public string Nmae { get; set; }
public string Value { get; set; }
}
Create the function which returns the list of Customers:
public List<Customer> GetCustomers()
{
var customers = new List<Customer>();
try
{
string sqlqry = "SELECT ID, Name, Value FROM Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con); // here _con is your predefined SqlConnection object
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
customers.Add(new Customer
{
ID = (int)dr["ID"],
Nmae = dr["Name"].ToString(),
Value = dr["Value"].ToString(),
});
}
}
catch (Exception ex)
{
// Handle exception here
}
return customers;
}
Then you can use this data as you want. For example, to fill your ComboBox with IDs you can use this:
public void Fill_Combo()
{
var customers = GetCustomers();
var ids = customers.Select(x => x.ID.ToString());
cmbBoxId.Items.AddRange(ids.ToArray());
}

How to bind datagridview's data source property to combobox?

I am trying to bind list of objects as a data source for data grid, on of the columns should be a combobox where selected value of the combobox should be value in the filed related in my object.
This is how I set the datasource of gridview :
var s = new BindingSource();
s.DataSource = dbc.GetResults();
dataGridView.DataSource = s;
dbc.GetResults(id) will return List and myClass which is
Class myClass
{
int productID{ set; get; }
int price{ set; get; }
}
And then I am initialling data grid view like this :
dataGridView.AutoGenerateColumns = false;
DataGridViewComboBoxColumn dgvc = new DataGridViewComboBoxColumn();
dgvc.HeaderText = "Products";
dgvc.DataSource = dbc.GetAllProducts();
dgvc.DisplayMember = "Name";
dgvc.ValueMember = "ID";
dataGridView.Columns.Add(dgvc);
dataGridView.Columns[0].DataPropertyName = "productID";
and dbc.GetAllProducts() returns list and :
Class Products
{
int ID;
string Name;
}
Here I expect that data grids get productID from myClass and pass it to combobox on each row, then the combo box gets the productID matches it with the ID in products column and then shows the Name property of it.
when I run this I get the error that DataGridViewComboBoxCell value is not valid.
You should use a dictionary to bind your property to your combo :
private Dictionary<int, string> cbProductVals= new Dictionary<int, string>();
Populate your dictionary with product objects and bind it on your grid column.
In your datagrid AutoGeneratingColumn event :
if (e.PropertyName == "productID")
{
DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
e.Column = cb;
cb.ItemsSource = cbProductVals;
cb.DisplayMemberPath = "Value";
cb.SelectedValuePath = "Key";
cb.SelectedValueBinding = new Binding("productID");
e.Column.Header = "product price";
}

Turning a database into a physical view using wpf xaml

So, I'm trying to connect to my database in a DataGrid view
In DatabaseDisplay.xaml.cs:
DataBaseConnection _dbView;
DataSet _dataSet;
DataRow _data;
public DatabaseDisplay()
{
InitializeComponent();
DataContext = new DataBaseConnection();
}
In DataBaseConnection.cs:
class DataBaseConnection
{
private string _dbConnector;
System.Data.SqlClient.SqlConnection _connectionToDb;
private System.Data.SqlClient.SqlDataAdapter _dataAdapter;
public DataBaseConnection(string dbConnector)
{
this._dbConnector = dbConnector;
}
// Get the data set generated by the sqlStatement
public DataSet GetDataSet(string sqlStatement)
{
_dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlStatement, _connectionToDb);
var dataSet = new DataSet();
_dataAdapter.Fill(dataSet);
return dataSet;
}
public void AddValues()
{
OpenConnection();
_dbConnector.Insert(1, "abc");
}
}
I am trying to connect to my database, and then populate the values in DataBaseDisplay.xaml which is pretty much a DataGrid and a Binding - nothing too fancy.
My issue is that when I try and pull DataContext = new DataBaseConnection(); it is giving me the error of: there is no argument given that corresponds to the required formal parameter 'dbConnector' of 'DataBaseConnection.DataBaseConnection'
Can anyone help me here?

DataGridViewComboBoxColumn DataSource?

I'm trying to get something set up in a DataGridView. It seems like this should be pretty straightforward but I'm having trouble. I want to display three columns:
CodeID
CodeName
ComboBox with DisplayMember of TypeName, ValueMember of TypeID
I want to be able to select from all possible values of TypeName. Here's my dilemma:
If I load all of this into one DataTable and set the DataGridView as the DataSource, I can display the existing TypeName for that record, but the combo box will not include any other values. If I set the DataSource for the DataGridViewComboBoxColumn to a separate DataTable that includes all possible TypeNames, the existing value is not displayed.
DataGridView is really annoying to work with so either a solution for this or a viable alternative would be appreciated.
Edit: it appears the issue is caused by my wanting to have a separate item for DisplayMember and ValueMember. The following works, if I don't worry about setting the ID as the ValueMember:
var typeColumn = new DataGridViewComboBoxColumn
{
DataSource = typeList,
DisplayMember = "Type",
ValueMember = "Type",
DataPropertyName = "Type"
}
If I do the following, the right types are selected, but I can't change the selection in the combo box:
var typeColumn = new DataGridViewComboBoxColumn
{
DataSource = typeList,
DisplayMember = "Type",
ValueMember = "TypeID",
DataPropertyName = "TypeID"
}
If I use the following I get a FormatException error as it's trying to populate:
var typeColumn = new DataGridViewComboBoxColumn
{
DataSource = typeList,
DisplayMember = "Type",
ValueMember = "TypeID",
DataPropertyName = "Type"
}
edit: typeList is a simple DataTable populated by the following:
SELECT DISTINCT IT.InsuranceTypeID, IT.[Type]
FROM InsuranceType IT
WHERE IT.ClientID = #ClientID
ORDER BY [Type]
I had a similar (I think) issue, and the solution for me was to set the DataSource for the DataGridViewComboBoxColumn before setting the DataSource for the DataGridView.
In my case, my DataSources are a List<T> and a BindingList<T> respectively but it should work the same with DataTables:
DataGridViewComboBoxColumn categoryColumn = (DataGridViewComboBoxColumn)_ItemsGrid.Columns["CategoryID"];
categoryColumn.DataSource = categories;
_ItemsGrid.DataSource = items;
Ok, I came up with an example ClientInfo and InsuranceDetails that I think might mimic what you are trying to do. Let me know if these details arent quite right. This example will populate the DataGridViewComboBox and set the value based on the InsuranceDetails (specifically at: InsurDetailz = all_insurance_types[2])
public partial class Form1 : Form
{
private ClientInfo _myClient;
private BindingList<InsuranceDetails> all_insurance_types =
new BindingList<InsuranceDetails>();
public Form1()
{
InitializeComponent();
DataGridView grid = new DataGridView();
grid.Dock = DockStyle.Fill;
grid.AutoGenerateColumns = true;
all_insurance_types.Add(new InsuranceDetails(1, "Health"));
all_insurance_types.Add(new InsuranceDetails(2, "Home"));
all_insurance_types.Add(new InsuranceDetails(3, "Life"));
var col = new DataGridViewComboBoxColumn
{
DataSource = all_insurance_types,
HeaderText = "Insurance Type",
DataPropertyName = "InsurDetailz",
DisplayMember = "ItType",
ValueMember = "Self",
};
_myClient = new ClientInfo {
InsurDetailz = all_insurance_types[2], Name = "Jimbo" };
grid.Columns.Add(col);
grid.DataSource = new BindingList<ClientInfo> { _myClient };
this.Controls.Add(grid);
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// make sure its updated
InsuranceDetails c = _myClient.InsurDetailz;
string name = _myClient.Name;
// Place breakpoint here to see the changes in _myClient
throw new NotImplementedException();
}
}
class ClientInfo
{
public string Name { get; set; }
public InsuranceDetails InsurDetailz { get; set; }
}
class InsuranceDetails
{
public int InsuranceTypeID { get; set; }
public String ItType { get; set; }
public InsuranceDetails Self { get { return this; } }
public InsuranceDetails(int typeId, String itType)
{
this.InsuranceTypeID = typeId;
this.ItType = itType;
}
}

populate dropdown list from a list of objects

In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities().
All I get is blanks in the dropdown list. Any idea why?
public List<City> GetCities()
{
List<City> cities = new List<City>();
Database db = new Database();
SqlConnection conn = db.GetConnection();
String sql = "SELECT * FROM CITIES";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
cities.Add(c);
}
db.CloseConnection();
return cities;
}
thanks
Did you set the DataTextField, DataValueField properties, and call DataBind?
At this point I would try to get the concept working as simply as possible, and then start adding things back in until you locate the problem. Start with a brand new page, add a DropDownList but don't touch the data source or change any properties, go directly into the codebehind and add this in Page_Load:
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataSource = new[] {
new { ID = 1, Name = "Alice" },
new { ID = 2, Name = "Mike" },
new { ID = 3, Name = "John" }
};
DropDownList1.DataBind();
Does it work? It does for me. Then try to change DataValueField, DataTextField, and DataSource to work with your customer list. Is it broken now? Then you know the problem is in the customer list somewhere, not with the way you're binding the data.
Have you called DataBind() method on the object you want to be populated ?
The issue resided in the City class which after a close inspection I've realised that the constructor was assigning the parameter received incorrectly. It's now working. Thanks!
public class City
{
int id;
string name;
public City(int id, string name)
{
this.id = id;
this.name = name;
}
public int Id
{
get { return id; }
set { id = value; }
}
public String Name
{
get { return name; }
set { name = value; }
}
}

Categories

Resources