Bind 2 separate columns to down drop list - c#

I am using a list box for the selection of file names pulled from SQL. The drop down works fine but is there a way I can bind a description also? The thought is to have the file name and description in the drop down list side by side. The file description is also a column in the same table.
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
layouts.DataSource = cmd.ExecuteReader();
layouts.DataTextField = "TextColumn";
layouts.DataValueField = "id";
layouts.DataBind();
con.Close();

This a example to bind bind two columns of data to a dropdown. Try it
using (SqlCommand cmd = new SqlCommand("select * from test1", con))
{
DataTable dt = new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
Dictionary<int,> lst = new Dictionary<int,>();
foreach (DataRow row in dt.Rows)
{
//Add values to Dictionary
string val = row[1].ToString() + " , " + row[2].ToString() + " , " + row[3].ToString();
lst.Add(Convert.ToInt32(row[0]), val);
}
DropDownList1.DataSource = lst;
DropDownList1.DataTextField = "Value";
DropDownList1.DataValueField = "Key";
DropDownList1.DataBind();
}

You can add an additional property (for example, NameDescription) to your model and use it:
public class File
{
public string Name { get; set; } // this is your file name property
public string Description { get; set; } // this is your description property
public string NameDescription => string.Format("{0} {1}", Name, Description); // the new property which contains name and description
}

Related

How to enter more than 1 row into dataGridView from textBox search

I am using the below code to search for the inputted textBox ID in an accessdb and returning the row of data to a dataGridView. When I search for a second ID, the first row in the GridView is replaced, How can I make it save multiple rows?
The end goal of this project is to allow the user to search as many ID's as they like and pull the corresponding row of data into the gridview to then save all into a csv.
private void searchButton_Click(object sender, EventArgs e)
{
conn1.Open();
//return ID, IMEI, ICCID, IMSI from dataBase
OleDbCommand cmd1 = new OleDbCommand("Select ID, IMEI,ICCID, IMSI from TBL where ID=#param1", conn1);
cmd1.Parameters.AddWithValue("#param1", txtScannedValue.Text);
OleDbDataReader reader1;
reader1 = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader1);
//dataGridView1.DataSource= dt;
if (dt.Rows.Count > 0)
{
((DataTable)dataGridView1.DataSource).ImportRow(dt.Rows[0]);
}
else
{
MessageBox.Show("No Data Found");
}
//reset textBox
txtScannedValue.Text = "";
conn1.Close();
}
What you are doing is - each time you press the searchButton_Click button you are running a query that returns 1 row only(ID=#param1) and then you are inserting ALL(which is always 1 in your case due to query) your searched rows to your dataGridView via .DataSource() bind.
To solve this I would recommend you to re-implement your data bindings:
I am assuming that DataTable is from ADO.NET so without changing a query you could bind your data something like this:
// this is pseudocode
private void searchButton_Click(object sender, EventArgs e) {
var row = (DataGridViewRow) dataGridView1.Rows[0].Clone();
var retrievedRow = getRowById(txtScannedValue.Text);
if (retrievedRow is null) return;
row.Cells[0].Value = retrievedRow.value1; // bind here you model fields
row.Cells[1].Value = retrievedRow.value2;
// ...
dataGridView1.Rows.Add(row);
}
private void getRowById(string id) {
conn1.Open();
OleDbCommand cmd1 = new OleDbCommand("Select ID, IMEI, TekNum, BatchNum, ICCID, IMSI from TBLTest1 where ID=#param1", conn1);
cmd1.Parameters.AddWithValue("#param1", id);
OleDbDataReader reader1;
reader1 = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader1);
DataRow row;
if (dt.Rows.Count > 0) {
row = dt.Rows[0];
}
conn1.Close();
return row;
}
I'd use a ListBox or ComboBox to present data they can recognize with the id available. To append rows, use DataTable.ImportRow.
Here a ComboBox is used to present, in this case employees and the DataGridView is initially populated with an empty DataTable.
Click a button to get a row to append to the underlying DataTable for the DataGridView.
Model and data operations
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
namespace AccessApplication.Classes
{
public class EmployeesOperations
{
public static string ConnectionString =>
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=NorthWind.accdb";
public static List<Employee> EmployeesList()
{
List<Employee> list = new List<Employee>();
using var cn = new OleDbConnection { ConnectionString = ConnectionString };
using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Employee()
{
Id = reader.GetInt32(0),
FirstName = reader.GetString(1),
LastName = reader.GetString(2)
});
}
return list;
}
public static DataTable EmptyDataTable()
{
using var cn = new OleDbConnection { ConnectionString = ConnectionString };
using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText =
"SELECT TOP 1 EmployeeID, FirstName, LastName FROM Employees";
cn.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
table.Rows.Clear();
return table;
}
public static DataTable SingleRow(int identifier)
{
using var cn = new OleDbConnection { ConnectionString = ConnectionString };
using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText =
"SELECT TOP 1 EmployeeID, FirstName, LastName " +
"FROM Employees WHERE EmployeeID = #Id";
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = identifier;
cn.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
return table;
}
}
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() => $"{FirstName} {LastName}";
}
}
Form code
public partial class EmployeeForm : Form
{
private readonly BindingSource _employeesBindingSource =
new BindingSource();
public EmployeeForm()
{
InitializeComponent();
_employeesBindingSource.DataSource = EmployeesOperations.EmployeesList();
EmployeesComboBox.DataSource = _employeesBindingSource;
dataGridView1.DataSource = EmployeesOperations.EmptyDataTable();
}
private void GetSingleEmployeeButton_Click(object sender, EventArgs e)
{
int id = ((Employee)EmployeesComboBox.SelectedItem).Id;
DataTable table = ((DataTable)dataGridView1.DataSource);
DataRow result = table.AsEnumerable()
.FirstOrDefault(row => row.Field<int>("EmployeeID") == id);
// only add if not already in the data grid view
if (result == null)
{
table.ImportRow(EmployeesOperations.SingleRow(id).Rows[0]);
}
}
}
The below code is now working for using the textbox to search the database and enter multiple rows of code into the dataGridView. The question was answered in the comments on the op by JohnG. Posting here for future reference.
private void searchButton_Click(object sender, EventArgs e)
{
conn1.Open();
//return ID, IMEI, BatchNum, ICCID, IMSI from dataBase
OleDbCommand cmd1 = new OleDbCommand("Select ID, IMEI, BatchNum, ICCID, IMSI from TBLTest1 where ID=#param1", conn1);
cmd1.Parameters.AddWithValue("#param1", txtScannedValue.Text);
OleDbDataReader reader1;
reader1 = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader1);
if (dt.Rows.Count > 0)
{
if (dataGridView1.DataSource != null) {
((DataTable)dataGridView1.DataSource).ImportRow(dt.Rows[0]);
}
else
{
dataGridView1.DataSource = dt;
}
}
else
{
MessageBox.Show("No Data Found");
}
//reset textBox
txtScannedValue.Text = "";
conn1.Close();
}

Getting specific column data from database in C#

I have created a search function that returns product data in a DataGridView (data is coming from local database), it does work but I need to have control over returned data in my grid view.
Current behavior
It returns all columns of database row in DataGridView
What I want
Returning only 2 or 3 columns of searched item instead of all columns
Create new list of searched items so I can edit those returned data
Logic
Search for product
Get product name and price from database, add custom quantity field make new list and add this item to show in DataGridView
Be able to change quantity field in DataGridView
Code
Here is my search code that returns all columns of product table
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (DataTable dt = new DataTable("Products"))
{
using (SqlCommand cmd = new SqlCommand("select * from Products where Id=#Id or Name like #Name", cn))
{
cmd.Parameters.AddWithValue("Id", searchBox.Text);
cmd.Parameters.AddWithValue("Name", string.Format("%{0}%", searchBox.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
// Following line will show all columns of founded product and replace it with next search result
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
selectedItems.DataSource = dt;
}
}
}
PS: Code above finds products based on id or name entered in search field and return all columns of product row.
Idea:
I think I can be able to create my list after finding product but the issue I'm facing is that I'm not sure how to get those specific columns from my dt (table row),
Here is what I've tried and failed (commented)
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (DataTable dt = new DataTable("Products"))
{
using (SqlCommand cmd = new SqlCommand("select * from Products where Id=#Id or Name like #Name", cn))
{
cmd.Parameters.AddWithValue("Id", searchBox.Text);
cmd.Parameters.AddWithValue("Name", string.Format("%{0}%", searchBox.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
//selectedItems.DataSource = dt; //<-- changed with lines below
List<string> items = new List<string>();
items.Add(dt); // <-- here is the issue (it expect to get string of my table row let say: Price column, but I don't know how to get Price column value from dt)
selectedItems.DataSource = items;
}
}
}
PS: code above is just idea and obviously I am not sure if it is best way to do it or not that's why I'm asking here :)
Any suggestions?
Update
I've created new class and added my data to that class as following
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Price { get; set; }
public string Qty { get; set; }
}
Then in my query I added
List<Item> itemList = new List<Item>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Item item = new Item();
item.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
item.Name = dt.Rows[i]["Name"].ToString();
item.Price = dt.Rows[i]["SellPrice"].ToString();
item.Qty = dt.Rows[i]["Qty"].ToString();
itemList.Add(item);
}
selectedItems.DataSource = itemList;
Now it does return data in my selectedItems but when I search for next product instead of adding it to the list it replace it with first product.
According to your sql query you are selecting all columns of the table.
To get the specific columns please change your sql query as such:
SqlCommand cmd = new SqlCommand("select Products.id, Products.name from Products where Id=#Id or Name like #Name", cn);
Thank you.
As per my understanding based on the comments, you are looking for some Linq code.
You only need to convert your result to a list that you could use.
Here is some code that might help you achieve this.
var result = dt.AsEnumerable().Select(x=> new {
Id = x["Id"],
Name = x["Name"],
Quantity = {Your Logic here}
});
selectedItems.DataSource = result;
You can then assign result to your datasource. You did not specify what your datasource is assigned to (selectedItems) so I do not know what type it is. but this should theoretically work. Just remove Quantity = {Your Logic here} from the code and see if it display's after which you could then just add it back and populate what you want Quantity to be
UPDATE
Because selectedItems is a DataGridView it requires a DataTable object to display the data. In which case you can not use an anonymous list as I created you would need something like this.
DataTable dtResult = new DataTable();
dtResult.Columns.Add("Id");
dtResult.Columns.Add("Name");
dtResult.Columns.Add("Quantity");
var result = dt.AsEnumerable().Select(x=> dtResult.Rows.Add(x["Id"],
x["Name"],
{Your Logic for Quantity here}
));
selectedItems.DataSource = result;
If you want to test this solution you can create a console application in c# and do something like where you can see the datasource is correct.
You could refer to the following code to show specific column data from database in winform datagirdview.
private void button1_Click(object sender, EventArgs e)
{
string str = "str";
SqlConnection connection = new SqlConnection(str);
connection.Open();
string sql = "select * from Product where Id=#Id or Name like #Name";
SqlCommand command = new SqlCommand(sql,connection);
command.Parameters.AddWithValue("#Id", textBox1.Text);
command.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
//Name=t.Field<string>("Name"), //The same way to show other columns data
Price = t.Field<string>("Price")
};
dataGridView1.DataSource = dt.ToList();
}
Result:
Database:

How to delete row from database depending on what is selected within a combobox

private void DeleteClient_Load(object sender, EventArgs e)
{
try
{
connection = new SqlConnection(new DatabaseConnection().cnnString.ToString());
connection.Open();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "Could not establish connection to the database.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cmd = new SqlCommand(new DatabaseAdd().addToComboBoxSE.ToString(), connection);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Id"] + ". " + dr["FirstName"] + " " + dr["Surname"]);
}
connection.Close();
}
Here i am adding items to a comboBox from a database. I am adding the ID(int), FirstName(varchar) and Surname(varchar) to each item for each row in the database.
My question is, how do i go about deleting a row from the database depending on a list item i have selected within the comboBox? I am able to do it when i just add the ID(int) to the comboBox but since i need the id, firstname and surname, i am unable to retrieve the ID from whatever list option i have selected.
Any help is appreciated. Thank you.
You need to create an instance of ComboBoxItem class and set its Value property to the id you want, then add it to your combobox.
The Class ComboBoxItem.cs:
public class ComboBoxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
Inside your foreach loop should be:
ComboBoxItem itm = new ComboBoxItem();
itm.Value = dr["Id"];
itm.Text = dr["Id"] + ". " + dr["FirstName"] + " " + dr["Surname"];
ComboBox1.Items.Add(itm);
You can get the selected item's id like this:
String selectedId = ((ComboBoxItem)(ComboBox1.SelectedItem)).Value.ToString();
Hope it helps.
Assuming that the Id is a numeric field, what you need to do is to split your string and extract the value of ID from the list. Since the format of the item is identical for all items, we can use the ". " as the separator string.
So, you can write something like this:
var str = selectedItem; // this is the value of selected item from the combo box and it's type is string. Example: "123. John Doe"
int ID = 0;
var str = selectedItem.Trim(); // this is the value of selected item from the combo box and it's type is string
var index = selectedItem.IndexOf(". ");
if (index > 1)
{
ID = Int32.Parse(selectedItem.Substring(0, index ) );
}
I was not sure
if you're asking to remove a row from the ComboBox once selected then
or delete from the db
This handles both, remove from Combo or delete from DB RowDeleter(string cmbName = "", bool deleteFromComboxBox )
Edit 1 updated the code based on comment:
//added optional parameter to pass combobox value after successfully record operations, or just call it
private void RowDeleter(ComboBox myComboBox)
{
try
{
SqlConnection conn = new SqlConnection(dataconnection);
SqlCommand cmd = new SqlCommand("myconn", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "yourtableset");
//look at what it is
String selectedId = (ComboBoxItem)(myComboBox.SelectedItem).Value.ToString();
DeleteRecord(selectedId);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
// delete Helper
private void DeleteRecord(string row)
{
return if (StringIsNullOrEmpty(row))
string sql = "DELETE FROM Table1 WHERE RowID = #row";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = someconnection;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#RowID";
RowParameter.SqlDbType = SqlDbType.string; //or int
RowParameter.IsNullable = false;
RowParameter.Value = row;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
deleteRecord.Connection.Close();
booksDataset1.GetChanges();
// sqlDataAdapter1.Fill(someDataset.WHatverEmployees);
}

Make dropdown list reference 2 sql columns

There are 2 columns, one with name and the other with email addresses. I want to be able to display the names from the name's column in a dropdown but user the email in the next column when the form is submitted on my asp page.
public void FillAssignedToDropdownOnsite()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["onsite_db"].ConnectionString);
string query = "SELECT Name, EmailAddress FROM OnsiteData ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
cmd.Connection.Open();
adpt.Fill(dt);
cmd.Connection.Close();
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataBind();
lstAssignedTo.Items.Insert(0, "Select Onsite Tech");
}
Sql table is OnsiteData
columns are name and emailaddress
Form has a dropdown that sends an email.
It seems that your tag is misplaced. Supposing that this is ASP.NET instead of ASP-Classic and lstAssignedTo is a DropDownList I suggest to use the DataValueField set to EmailAddress
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataValueField = "EMailAddress";
lstAssignedTo.DataBind();
when needed you could extract the email address for the selected user reading the Value property
if(lstAssignedTo.SelectedValue != null)
{
string email = lstAssignedTo.SelectedValue.ToString();
......
}
Not sure it's what you want :
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataValueField = "EmailAddress"
lstAssignedTo.DataBind();
lstAssignedTo.Items.Insert(0, "Select Onsite Tech");
Like this the name is displayed and you can get the corresponding email with
var value = lstAssignedTo.SelectedValue;

DataGridViewComboBoxColumn save SelectedText for each row in SQL

This is T-SQL for Inserting data from datagridview into SQL Table but the issue is that one of datagridview's column is DataGridViewComboBoxColumnand I need for each row save particular selected item in combobox. May I ask how it can be done?
public DataGridViewComboBoxColumn cbColumn;
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
try
{
string delCmdTxt = "DELETE FROM PRONAJEM WHERE NA_CISLKU=#NA_CISLKU";
SqlCommand cmdDel = conn.CreateCommand();
cmdDel.Parameters.AddWithValue("#NA_CISLKU",VybraneCisku);
cmdDel.CommandText = delCmdTxt;
cmdDel.Transaction = sqlTrans;
cmdDel.ExecuteNonQuery();
string insert_sql = "INSERT INTO PRONAJEM(DATUM,PLODINA,CENAMJ,MNOZSTVIMJ,PRIKAZ,NA_ZUSTA,NA_CISLKU,RODNECISLO)VALUES" +
"(#DATUM,#PLODINA,#CENAMJ,#MNOZSTVIMJ,#PRIKAZ,#NA_ZUSTA,#NA_CISLKU,#RODNECISLO)";
using (SqlCommand sqlcom = conn.CreateCommand())
{
sqlcom.CommandText = insert_sql;
sqlcom.Transaction = sqlTrans;
sqlcom.Parameters.Add("#DATUM", SqlDbType.Date); //Replace with whatever the correct datatypes are
sqlcom.Parameters.Add("#PLODINA", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#CENAMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#MNOZSTVIMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#PRIKAZ", SqlDbType.Date);
sqlcom.Parameters.Add("#NA_ZUSTA", SqlDbType.Decimal);
sqlcom.Parameters.Add("#NA_CISLKU", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#RODNECISLO", SqlDbType.NVarChar);
var validRows = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells["DATUM"].Value != null);
foreach (DataGridViewRow row in validRows)
{
sqlcom.Parameters[0].Value = row.Cells["DATUM"].Value;
sqlcom.Parameters[1].Value = row.Cells["POLOZKAcb"].Value;
sqlcom.Parameters[2].Value = row.Cells["CENAMJ"].Value;
sqlcom.Parameters[3].Value = row.Cells["MNOZSTVIMJ"].Value;
sqlcom.Parameters[4].Value = row.Cells["PRIKAZ"].Value;
sqlcom.Parameters[5].Value = row.Cells["NA_ZUSTA"].Value;
sqlcom.Parameters[6].Value = VybraneCisku;
sqlcom.Parameters[7].Value = VybraneRodneCislo;
sqlcom.ExecuteNonQuery();
}
sqlcom.Dispose();
}
sqlTrans.Commit();
This is the creating of DataGridViewComboBoxColumn:
string query = "SELECT * FROM PLODINY ";
SqlCommand newcom = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader= newcom .ExecuteReader();
List<string> listPlodiny = new List<string>();
while (reader.Read())
{
listPlodiny.Add(reader.GetString(reader.GetOrdinal("PLODINA")) + "-" + Decimal.Parse(reader["CENAZAQ"].ToString()).ToString());
for (int i = 0; i <= listPlodiny.Count() - 1; i++)
{
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.DataSource = listPlodiny;
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
Thank you all for your time
I think because you not set a .ValueMember property for DataGridViewComboBoxColumn...
You need to set
.ValueMember - set Value for Cell from DataSource's property.
This value will be referenced with Column.DataPropertyName's value.
.DisplayMember- Value of this will be used for diplay text in dropdown cell
Try next(updated for using of DataTable as DataSource in DataGridViewComboBoxColumn:
DataTable dtPlodiny;
using(SqlConnection sqlConn = new SqlConnection(conn))//conn - your connection string
{
string sqlQuery = #"SELECT ID, Description FROM PLODINY"; //better practice use only fields you need
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtPlodiny);
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.Name = "POLOZKAcb"
cbColumn.DataSource = dtPlodiny; //Changed with DataTable
//add next two rows
cbColumn.DisplayMember = "Description" //property from .Datasource you want to show for user
cbColumn.ValueMember = "ID" //property from .Datasource you want use as Value - reference to DataPropertyName
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
If your datagridview use always same columns,
then I think easally if you use a predefined columns(created/added through Designer). Then you can set a name for every column and use it in code as object:
this.MyColumnPolozka.Name...
for example...
if you donot get correct value from row.Cells(0).Value then try casting it to dropdownlist

Categories

Resources