loading combobox with datasource - c#

i want to fill a combobox with data from the database when the page load
I had written the code as below
private void QuotationForm_Load(object sender, EventArgs e)
{
MessageBox.Show("hghjgvhg");
comboboxload();
}
public void comboboxload()
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobecode from jobcodemastertable",oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("jobpk", typeof(int));
dt.Columns.Add("jobcode", typeof(string));
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
oleDbConnection1.Close();
}
it doesnot deturns an error or exception but doesnot load the combobox with data values

try this
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";

You may need to bind datatable's view with combo box
cmbjobcode.DataSource = dt.DefaultView;

You're missing the DataBind method
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
//here
cmbjobcode.DataBind();
oleDbConnection1.Close();

You have to call DataBind method on your combo. Thats why its not populating.

Related

how to bind datatable to datagridview in c#

I need to bind my DataTable to my DataGridView.
i do this:
DTable = new DataTable();
SBind = new BindingSource();
//ServersTable - DataGridView
for (int i = 0; i < ServersTable.ColumnCount; ++i)
{
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
}
for (int i = 0; i < Apps.Count; ++i)
{
DataRow r = DTable.NewRow();
r.BeginEdit();
foreach (DataColumn c in DTable.Columns)
{
r[c.ColumnName] = //writing values
}
r.EndEdit();
DTable.Rows.Add(r);
}
SBind.DataSource = DTable;
ServersTable.DataSource = SBind;
But all i got is DataTable ADDS NEW columns to my DataGridView.
I don't need this, i just need to write under existing columns.
Try this:
ServersTable.Columns.Clear();
ServersTable.DataSource = SBind;
If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:
for (int i = 0; i < ServersTable.ColumnCount; ++i) {
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
}
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.
// I built my datatable first, and populated it, columns, rows and all.
//Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.
BindingSource SBind = new BindingSource();
SBind.DataSource = dtSourceData;
ADGView1.AutoGenerateColumns = true; //must be "true" here
ADGView1.Columns.Clear();
ADGView1.DataSource = SBind;
//set DGV's column names and headings from the Datatable properties
for (int i = 0; i < ADGView1.Columns.Count; i++)
{
ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
}
ADGView1.Enabled = true;
ADGView1.Refresh();
foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable StudentDataTable = new DataTable("Student");
//perform this on the Load Event of the form
private void AddColumns()
{
StudentDataTable.Columns.Add("First_Int_Column", typeof(int));
StudentDataTable.Columns.Add("Second_String_Column", typeof(String));
this.dataGridViewDisplay.DataSource = StudentDataTable;
}
}
//Save_Button_Event to save the form field to the table which is then bind to the TableGridView
private void SaveForm()
{
StudentDataTable.Rows.Add(new object[] { textBoxFirst.Text, textBoxSecond.Text});
dataGridViewDisplay.DataSource = StudentDataTable;
}
for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps :
step 1 - get all Users by :
public DataTable getAllUsers()
{
OracleConnection Connection = new OracleConnection(stringConnection);
Connection.ConnectionString = stringConnection;
Connection.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("semect * from Users");
cmd.CommandType = CommandType.Text;
cmd.Connection = Connection;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}
return dataSet.Tables[0];
}
step 2- set the return result to DataGridView :
public void setTableToDgv(DataGridView DGV, DataTable table)
{
DGV.DataSource = table;
}
using example:
setTableToDgv(dgv_client,getAllUsers());

Putting Values in Controls when dynamically creating a form

I have been working on an issue for a while and I finally figured it out. I was trying to set a control when the Form is being initialize. I am thinking that the control's value isn't being set is because the control has been drawn yet (CORRECT ME IF I AM WRONG).
My partial form code
//in form 1
....
private void button2_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Owner = this;
form.Show(this);
}
....}
public Form2()
{
InitializeComponent();
setData(); //Sets a datagridview's combobox column and databinds a datatable
setGrid(); //Sets each row in the datagridview combobox's value to a string
}
private void setData()
{
gvTest.AllowUserToAddRows = false;
string strConn = "server=10.253.3.185;database=petersun-test1;user id=ctore;password=cqi$$;connection timeout=30";
SqlConnection conn = new SqlConnection(strConn);
DataTable dit = new DataTable();
try
{
conn.Open();
string sql = "SELECT LTRIM(RTRIM(COLUMN_NAME)) as ColumnName from INFORMATION_SCHEMA.COLUMNS where Table_Name='coproc' order by ORDINAL_POSITION";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dit);
DataGridViewComboBoxColumn dcDatabasefields = new DataGridViewComboBoxColumn();
dcDatabasefields.DataPropertyName = "ColumnName";
dcDatabasefields.HeaderText = "Database Field Name";
dcDatabasefields.Name = "dbFields";
dcDatabasefields.DisplayMember = "ColumnName";
dcDatabasefields.ValueMember = "ColumnName";
dcDatabasefields.Width = 200;
BindingSource bsourceFields = new BindingSource();
bsourceFields.DataSource = dit;
dcDatabasefields.DataSource = bsourceFields;
dcDatabasefields.DataSource = dit; // bsourceFields;
gvTest.Columns.Add(dcDatabasefields);
}
finally
{
conn.Close();
}
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("options");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["options"] = "A";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["options"] = "C";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["options"] = "D";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["options"] = "E";
dt.Rows.Add(dr);
gvTest.DataSource = dt;
}
private void setGrid()
{
foreach(DataGridView Row in gvGrid.Rows)
{
Row.Cells[0].Value = "string";
}
}
So what I think is happening is:
1. The component is getting initialized
2. Creates the datagridview with columns
3. Sets the column values
4. Draws the form
Is my thinking correct? My question is what form event should I set the control's value? I did some research and I am thinking on the PAINT event, but I am not sure either. Could someone explain the Form's life cycle in some detail or point me to somewhere.
Thanks
I just added the coded into the Form_load and it added the values to the grid

How to bind a ListBox to a DataTable from a session object?

I have a session object that contains a DataTable from my previous page,
and i would like to bind this DataTable to a ListBox.
I'v done this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["bestStocks"] !=null)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["bestStocks"];
DataView dv = new DataView(dt);
BestStockslb.DataSource = dt;
BestStockslb.DataBind();
}
}
}
I get this result:
Any suggestion?
thanks,
liron
It seems you have forgot the DataTextField and DataValueField
dt = (DataTable)Session["bestStocks"];
DataView dv = new DataView(dt);
BestStockslb.DataSource = dt;
BestStockslb.DataTextField = "Name";
BestStockslb.DataValueField = "ID";
BestStockslb.DataBind();
Change this line:
BestStockslb.DataSource = dt;
To:
BestStockslb.DataSource = dt.DefaultView;
And you also need to set the DataTextField and DataValueField Properties of BestStockslb to link to the required fields in the returned data. This is why you are getting the DataRowView output.
You could also remove DataView dv = new DataView(dt); as it looks like you are not using it.

Binding GridViewComboBoxColumn to a datasource

I already know how to specify the datasource but afther doing that it is not populated yet so i was thinking you need some kind of bind() command to populate the comboboxcolumn in the edit form
This below is how i bind the datasource to the comboboxcolumn (and yes i am sure that ds has data rows in it)
(ASPxGridView4.Columns["Naam"] as GridViewDataComboBoxColumn).PropertiesComboBox.DataSource = ds as DataSet;
So could anyone tell me how i can now populate the comboboxcolumn in edit mode?
Edit
protected void ASPxGridView4_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
{
if (dt.Rows.Count < 1)
{
ds = Session["ds"] as DataSet;
}
GridViewDataComboBoxColumn column = (ASPxGridView4.Columns["Naam"] as GridViewDataComboBoxColumn);
column.PropertiesComboBox.DataSource = ds.Tables[0];
column.PropertiesComboBox.ValueField = "Naam";
column.PropertiesComboBox.ValueType = typeof(string);
column.PropertiesComboBox.TextField = "Naam";
}
Here is the code which should work:
DataSet dataSet = ds as DataSet;
GridViewDataComboBoxColumn column = (ASPxGridView4.Columns["Naam"] as GridViewDataComboBoxColumn);
column.PropertiesComboBox.DataSource = dataSet.Tables[0];
column.PropertiesComboBox.ValueField = "SomeValueField";
column.PropertiesComboBox.ValueType = typeof(int); // type of the SomeValueField
column.PropertiesComboBox.TextField = "SomeTextField";
Also, please refer to the GridViewDataComboBoxColumn Class topic.
UPDATE Your code should be implemented in the CellEditorInitialize event as shown below:
protected void ASPxGridView1_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e) {
if(e.Editor is ASPxComboBox) {
ASPxComboBox combo = ((ASPxComboBox)e.Editor);
combo.DataSource = dataSet.Tables[0];
combo.TextField = "Naam";
combo.ValueField = "Naam";
combo.DataBindItems();
}
}

c# converting from System.Data.DataRowView to string

i have a combobox whose datasource is a datatable. i need to loop through the items in the combobox, but how would i do this? i need to be able to convert each object of type 'System.Data.DataRowView' to string. any advice greatly appreciated!#
Based on your recent questions, it sounds like you are trying to figure out how to find or set the selected item in the combobox based on the text displayed in the item. I am not exactly sure how you have things set up, but please look at the following code and see if it helps:
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
dt.Rows.Add(3, "C");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
// use SelectedValue to select the item with ID == 2
comboBox1.SelectedValue = 2;
// use FindStringExact() to find the index of text displayed in the item
comboBox1.SelectedIndex = comboBox1.FindStringExact("C");
}
and using a combobox as set up above, you can get the text of the display member like this:
private void button2_Click(object sender, EventArgs e)
{
foreach (var item in comboBox1.Items)
MessageBox.Show(((DataRowView)item)["Name"].ToString());
}
Workaround for the same, hope it helps:
Convert the dataview source back to datatable and then loop through it.
DataView dt = (DataView)comboBox1.DataSource;
DataTable s = dt.Table;
foreach(DataRow dr in s.Rows)
MessageBox.Show(dr[0].ToString());
Well... to loop through a combobox, use (slightly pseudocoding, please don't c+p without working on the code):
var newItems = new List<string>();
for(var i = 0; i < combobox1.Items.Count; i++)
{
newItems.Add(combobox1.items[i].Text);
}
Then to access each item, use:
foreach(item in newItems)
{
var newVariable1 = item;
}
More info and your current code would be cool, I'd be able to help you more specifically with your problem that way.
Solution:
DataTable DtShow=new DataTable();
for (int i = 0; i < DtShow.Rows.Count; i++)
{
Console.WriteLine(DtShow.Rows[i].Field<string>(0));
}
** Field<string>(0) Column number start from 0
Hope this helps someone some day. Took me a while to come up with a solution for making a checkedboxlist populate from SQL server.
public partial class MemberSearch : Form
{
List<string> DataList = new List<string>(1);
public void GetTypesTable()
{
var CONEX = Properties.Settings.Default.Server_1_Conn;
var sql = "SELECT Type_List FROM List_Member_Types;";
DataTable dt = new DataTable();
using (SqlConnection c = new SqlConnection(CONEX))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
sda.Fill(dt);
DataView view = new DataView(dt);
DataTable s = dt;
foreach (DataRow ROW in s.Rows)
DataList.Add(ROW[0].ToString());
ckLstBox_MemTypes.DataSource = DataList;
}
}

Categories

Resources