Set Value of ComboBoxColumn DataGridView - c#

i have a question. I have a ComboBoxColumn and want to populate Data from Database via ComboBox Variable inside this Column. How can i achieve this.
This snippet I tried doesnt doesn't work
ComboBoxColumn.Items.AddRange("One", "Two", "Three", "Four");
My problem is i getting Data inside another function that will save all the values inside a ComboBox Variable (that every Functions has Access to) and i want to fill the Cell in DataGridView via Column-/Row-Index like this:
private ComboBox ComboBoxItems
private void datagridview_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
int col1 = datagridview.Columns["datagridview_col1"].Index;
int col2 = datagridview.Columns["datagridview_col2"].Index;
int col3 = datagridview.Columns["datagridview_col2"].Index;
if ((e.ColumnIndex == col1))
{
fill_col2();
}
else if ((e.ColumnIndex == col2))
{
datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ComboBoxItems1;
foreach (var item in ComboBoxItems1.Items)
{
Console.WriteLine(ComboBoxItems1.Items.Count);
Console.WriteLine(item.ToString());
}
if (!String.IsNullOrEmpty(section))
{
fill_col3();
}
}
else if ((e.ColumnIndex == col3))
{
datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ComboBoxItems2;
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading Data!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Has anyone an idea for a good working solution?

If you want to set the ComboboxColumn datasource, you can set it while you define the ComboboxColumn.
var ComboCol= new DataGridViewComboBoxColumn
{
HeaderText = "ComboCol",
Name = "ComboCol",
DataSource = new List<string> {"One", "Two", "Three", "Four"}
};
Then before fill the combobox with the data from database, you need to convert the cell to DataGridViewComboBoxCell first.
DataSet ds;
string connetionString = #"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From TestTable", conn);
ds = new DataSet();
sda.Fill(ds, "TableName");
}
DataGridViewComboBoxCell ComboCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["CommonCol1"].Value = row[0];
ComboCell= (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["ComboCol"]);
ComboCell.Value = row[1].ToString();
}
Hope this can help you.

Related

comboBox.SelectedValue to fetch id on sql server

Im having trouble fetching ID of selected value from combobox, cna i get some help? the program should get the id of the selected string in the combobox from database.
private void GetValues_Click(object sender, RoutedEventArgs e)
{
ReportesAsistenciaTableAdapter ada = new ReportesAsistenciaTableAdapter();
DataTable dt = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
if (dt.Rows.Count > 0)
{
DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
EstudiantesList.ItemsSource = dtNew.ToString();
}
else
{
Estudiantes1TableAdapter studentsAdapter = new Estudiantes1TableAdapter();
DataTable dtStudents = studentsAdapter.GetDataByClaseID((int)selectClass.SelectedItem);
foreach (DataRow row in dtStudents.Rows)
{
ada.InsertQuery((int)row[0], (int)selectClass.SelectedItem, dateBox.Text, "", row[1].ToString(), selectClass.Text) ;
}
DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
EstudiantesList.ItemsSource = dtNew.ToString();
}

Populate dropdown from database, which is place inside Gridview in Windows Application using c#

How to populate a drop down from database which is placed inside a gridview and handle the selected index change event of that drop down in windows application using c#
You can bind the IList implementation with the dropdown or combo box.
Instead of enum.getvalues, you can bind any IList and specify the display property name.
DataGridViewComboBoxColumn CreateComboBoxWithEnums()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = Enum.GetValues(typeof(Title));
combo.DataPropertyName = "Title";
combo.Name = "Title";
return combo;
}
Then use below code to add the column to the grid view columns collection
dataGridView1.Columns.Add(CreateComboBoxWithEnums());
Please note that Unlike the ComboBox control, the DataGridViewComboBoxCell does not have SelectedIndex and SelectedValue properties. Instead, selecting a value from a drop-down list sets the cell Value property.
Reference: this documentation
I hope you have already got how to populate combobox inside Datagridview. You can try this to handle selected index change of Datagridview Combobox as shown below.
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int column=excelGridview.CurrentCell.ColumnIndex;
int row = excelGridview.CurrentCell.RowIndex;
int country = Convert.ToInt32(((ComboBox)sender).SelectedValue);
if (column == 7)
{
MyConnect myCnn = new MyConnect();
String connString = myCnn.getConnect().ToString();
SqlConnection conn;
SqlCommand command;
conn = new SqlConnection(connString);
command = new SqlCommand();
if (country > 0)
{
try
{
conn.Open();
string query = "select regionID FROM countryinfo country WHERE country.ID=" + country + "";
command = new SqlCommand(query, conn);
SqlDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
var currentcell = excelGridview.CurrentCellAddress;
DataGridViewComboBoxCell cel = (DataGridViewComboBoxCell)excelGridview.Rows[currentcell.Y].Cells[8];
cel.Value = Convert.ToInt64(dt.Rows[0]["regionID"]);
conn.Close();
}
catch (Exception ex1)
{
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
catch (Exception) { }
}
You can get help from here
It looks like as shown in below image

retrieving values from multiple columns in asp drop down

I've got a dropdown whose values are retrieved from a database. I am retrieving ID and name from the database.
public void GetDepartment_temp()
{
try
{
DataTable dt = new DataTable();
listBoxDepartment.ClearSelection();
Get_Department objDAL = new Get_Department();
dt = objDAL.Get_Hospital_Department();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
listBoxDepartment.Items.Add(new ListItem(row["department_name"].ToString(), row["department_id"].ToString()));
}
}
}
catch (Exception) { }
}
I've got to show the number of employees of each department in the text box. Suppose a user selects human department, then the text box should display the number of employees in that department.
For the ListBox, only two values from the database can be retrieved. How can I show the number of employee in this condition?
public DataTable Get_Hospital_Department()
{
try
{
DataTable dt = new DataTable();
dt = DbAccessHelper.ExecuteDataSet("p_get_hospital_department", true).Tables[0];
return dt;
}
catch (Exception) { return null; }
}
CREATE PROCEDURE [dbo].[p_get_hospital_department]
AS
BEGIN
SET NOCOUNT ON;
SELECT department_id
,department_name
FROM [dbo].[tbl_hospital_department];
END
The statement For the ListBox, only two values from the database can be retrieved. is not correct. You can populate the datatable with as many fields as you want. However, you can set only the Value and text attributes of the Listbox item as you have done.
Change the stored procedure code to fetch the employee count also.
Mark your datatable dt as static and public.
Fetch the datable and you can play with the data as you want. You can fetch the employee count in the textbox on listview selected index changed as shown below:
public static DataTable dt = new DataTable();
public void GetDepartment_temp()
{
try
{
string connString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command =
new SqlCommand(
"select Department.DepartmentID, Department.[Department Name], count( Department.DepartmentID) as empCount from Department join Employee on Department.DepartmentID = Employee.DepartmentID group by Department.DepartmentID, Department.[Department Name]",
connection);
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
dt.PrimaryKey = new DataColumn[] {dt.Columns["DepartmentID"]};
ListBox1.ClearSelection();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
ListBox1.Items.Add(new ListItem(row["Department Name"].ToString(),
row["DepartmentID"].ToString()));
}
}
}
catch (Exception ex)
{
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRow dr = dt.Rows.Find(Convert.ToInt32(ListBox1.SelectedItem.Value));
TextBox5.Text = dr["empCount"].ToString();
}

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" });
}

Add an item to combobox before binding data from the database

I had a combobox in a Windows Forms form which retrieves data from a database. I did this well, but I want to add first item <-Please select Category-> before the data from the database. How can I do that? And where can I put it?
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category, Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}
You could either add the default text to the Text property of the combobox like this (preferred):
CBParent.Text = "<-Please select Category->";
Or, you could add the value to the datatable directly:
da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
public class ComboboxItem
{
public object ID { get; set; }
public string Name { get; set; }
}
public static List<ComboboxItem> getReligions()
{
try
{
List<ComboboxItem> Ilist = new List<ComboboxItem>();
var query = from c in service.Religions.ToList() select c;
foreach (var q in query)
{
ComboboxItem item = new ComboboxItem();
item.ID = q.Id;
item.Name = q.Name;
Ilist.Add(item);
}
ComboboxItem itemSelect = new ComboboxItem();
itemSelect.ID = "0";
itemSelect.Name = "<Select Religion>";
Ilist.Insert(0, itemSelect);
return Ilist;
}
catch (Exception ex)
{
return null;
}
}
ddlcombobox.datasourec = getReligions();
CBParent.Insert(0,"Please select Category")
You should add "Please select" after you bind data.
var query = from name in context.Version
join service in context.Service
on name.ServiceId equals service.Id
where name.VersionId == Id
select new
{
service.Name
};
ddlService.DataSource = query.ToList();
ddlService.DataTextField = "Name";
ddlService.DataBind();
ddlService.Items.Insert(0, new ListItem("<--Please select-->"));
There are two quick approaches you could try (I don't have a compiler handy to test either one right now):
Add the item to the DataTable before binding the data.
You should be able to simply set CBParent.Text to "<- Please Select Category ->" after you bind the data. It should set the displayed text without messing with the items.
void GetProvince()
{
SqlConnection con = new SqlConnection(dl.cs);
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT ProvinceID, ProvinceName FROM Province", con);
DataTable dt = new DataTable();
int i = da.Fill(dt);
if (i > 0)
{
DataRow row = dt.NewRow();
row["ProvinceName"] = "<-Selecione a Provincia->";
dt.Rows.InsertAt(row, 0);
cbbProvince.DataSource = dt;
cbbProvince.DisplayMember = "ProvinceName";
cbbProvince.ValueMember = "ProvinceID";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources