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" });
}
Related
I have a form with two combo boxes which both have a list from a database. In this case one is a list of countries and based on the value selected there, the second list is updated to show only the cities that belong to the selected country. After that, the values are combined and stored in my program like "city, country".
When I open my form I retrieve that information and separate the values back to just country and city. All working. The trouble I have now is that the comboboxes should display the retrieved values if the correspond to a value found in the list/database. I tried as shown below, but that is not working. I guess it has something to do with adding a new row to the database to show "--Select Country--" and "--Select City--".
I hope you can point me in the right direction. Thank you all in advance for your replies.
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
public partial class FormPropertyEditor : Form
{
//Connect to local database.mdf
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
#"C:\Users\gleonvanlier\AppData\Roaming\Autodesk\ApplicationPlugins\MHS Property Editor\Database.mdf;" +
"Integrated Security=True;Connect Timeout=30;User Instance=False;");
DataRow dr;
public FormPropertyEditor()
{
InitializeComponent();
ReadProperties();
refreshdata();
}
public void refreshdata()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCountries Order by CountryName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select Country--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCountry.ValueMember = "CountryID";
comboBoxCountry.DisplayMember = "CountryName";
comboBoxCountry.DataSource = dt;
comboBoxCountry.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCountry.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxCountry.SelectedValue.ToString() != null)
{
int CountryID = Convert.ToInt32(comboBoxCountry.SelectedValue.ToString());
refreshstate(CountryID);
}
}
public void refreshstate(int CountryID)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCities where CountryID= #CountryID Order by CityName", con);
cmd.Parameters.AddWithValue("CountryID", CountryID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, 0, "--Select City--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCity.ValueMember = "CityID";
comboBoxCity.DisplayMember = "CityName";
comboBoxCity.DataSource = dt;
comboBoxCity.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCity.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void ReadProperties()
{
string progId = "Inventor.Application";
Type inventorApplicationType = Type.GetTypeFromProgID(progId);
Inventor.Application invApp = (Inventor.Application)Marshal.GetActiveObject(progId);
//Get the active document in Inventor
Document oDoc = (Document)invApp.ActiveDocument;
ReadProperties readProperties = new ReadProperties();
//Read Customer
string txtCustomer = readProperties.ReadCustomProperty("Customer", oDoc).ToString();
this.textBoxCustomer.Text = txtCustomer;
//Read Location
string txtLocation = readProperties.ReadCustomProperty("Location", oDoc).ToString();
try
{
string[] location = txtLocation.Split(',', ' ');
string city = location[0];
string country = location[1];
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
}
catch (Exception e)
{
string city = string.Empty;
string country = string.Empty;
}
}
This solved it:
comboBoxCountry.SelectedIndex = comboBoxCountry.FindStringExact(country);
comboBoxCity.SelectedIndex = comboBoxCity.FindStringExact(city);
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.
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
I have a Dropdownlist in a Gridview and i have to show the records associated with every id.And the ID contains more than 10 records so how can i show them??
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("DropDownList1");
//int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select LastName from Profile_Master", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "LastName";
ddl.DataBind();
}
}
FillSelect(myDropDownList, "--select--", "0", true);
public static void FillSelect(DropDownList DropDown, string SelectItemText, string SelectItemValue, bool includeselectitem)
{
List<PhoneContact> obj_PhoneContactlist = getAll();
if (obj_PhoneContactlist != null && obj_PhoneContactlist.Count > 0)
{
DropDown.DataTextField = "PhoneContactName";
DropDown.DataValueField = "id";
DropDown.DataSource = obj_PhoneContactlist.OrderBy(o => o.PhoneContactName);//linq statement
DropDown.DataBind();
if (includeselectitem)
DropDown.Items.Insert(0, new ListItem(SelectItemText, SelectItemValue));
}
}
public static List<PhoneContact> getAll()
{
obj_PhoneContactlist = new List<PhoneContact>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
obj_SqlConnection = new SqlConnection(QueryString);
obj_SqlCommand = new SqlCommand("spS_GetMyContacts");
obj_SqlCommand.CommandType = CommandType.StoredProcedure;
obj_SqlConnection.Open();
obj_SqlCommand.Connection = obj_SqlConnection;
SqlDataReader obj_result = null;
obj_SqlCommand.CommandText = "spS_GetMyContacts";
obj_result = obj_SqlCommand.ExecuteReader();
//here read the individual objects first and append them to the listobject so this we get all the rows in one list object
using (obj_result)
{
while (obj_result.Read())
{
obj_PhoneContact = new PhoneContact();
obj_PhoneContact.PhoneContactName = Convert.ToString(obj_result["PhoneContactName"]).TrimEnd();
obj_PhoneContact.PhoneContactNumber = Convert.ToInt64(obj_result["PhoneContactNumber"]);
obj_PhoneContact.id = Convert.ToInt64(obj_result["id"]);
obj_PhoneContactlist.Add(obj_PhoneContact);
}
}
return obj_PhoneContactlist;
}
I have done this to get my phonecontacts which are in the data base into dropdown you can change the stored procedures and the values according to your need.
Hope this helps:D
We just ran into this issue where I work. Our way around this problem was to first get the DropDownLists UniqueID. This is basically a Client ID. Inside of that ID is a reference to the row of the GridView that it was selected from. THE ONLY PROBLEM is that it seems to add 2 to the row count. So if you select Row 1's DropdownList, the Unique ID will bring you a reference to the 3rd row. So:
Get the unique ID > Split it however you need to to get the row > use the row number to get the values you need.
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);
}
}