I am loading two combo boxes with two different datasources from sql using a datatable and i'm loading it when the form loads but i dont know the reason only one combo box is filled (one at the top always fills the other one doesn't) and i have checked the datatables they are working fine
private void Form1_Load(object sender, EventArgs e)
{
if (comboBox2.Text == "")
{
customer cc1 = new customer();
comboBox2.DataSource = cc1.getplatenumber();
comboBox2.ValueMember = "Platenumber";
comboBox2.DisplayMember = "Platenumber";
comboBox2.Items.Add("Platenumber");
}
if (comboBox1.Text == "")
{
customer cc = new customer();
DataTable dt = cc.getitems();
comboBox1.DataSource = dt;
comboBox1.ValueMember = "Item_no";
comboBox1.DisplayMember = "Itemname";
comboBox1.Items.Add("Itemname");
comboBox1.SelectedIndex = 0;
}
}
any help ?
Step through the code
Ensure that the code inside the 2nd if block runs, as Rohit suggests
Verify that dt is filled as you expect
Check the strings you're using to extract data - are "Item_no" and "Itemname" correct?
Related
i have one Datagridview and two combobox (related) When I click on dataGridView1_CellMouseClick cmbSehir.Text changes as I want. but cmbilce.Text does not change as I want!. Where do i make mistakes. I hope I made myself clear. Thanks for helping.
private void frmMusteriEkle_Load(object sender, EventArgs e)
{
GetSehir();
GetDatagridview();
}
private void GetSehir() {
db.connect();
db.SqlQuery("select * from iller");
DataTable dt = db.GeTDataTable();
DataRow dr = dt.NewRow();
dr["id"] = 0;
dr["sehir"] = "Seçiniz:";
dt.Rows.InsertAt(dr, 0);
cmbSehir.DataSource = dt;
cmbSehir.ValueMember = "id";
cmbSehir.DisplayMember = "sehir";
db.disconnect();
}
private void cmbSehir_SelectionChangeCommitted(object sender, EventArgs e)
{
if (cmbSehir.SelectedIndex != 0)
{
db.connect();
db.SqlQuery("select * from ilceler where il_id = ?");
db.command.Parameters.AddWithValue("#p", cmbSehir.SelectedValue);
DataTable dt = db.GeTDataTable();
cmbilce.DataSource = dt;
cmbilce.ValueMember = "id";
cmbilce.DisplayMember = "ilceler";
db.disconnect();
}
else
{
cmbilce.DataSource = null;
}
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
cmbSehir.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
cmbilce.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
}
Without seeing what GetDatagridview method does, I will assume from the lines…
cmbSehir.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
cmbilce.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
that these combo boxes are related to the data contained in columns 4 and 5. If the combo boxes have the same data source as the DataGridView then it is possible to bind all three controls to the same DataSource. After binding all three components to the same data source, clicking on a cell in the grid will automatically change the combo boxes and vice versa… changing a combo box will change the selection in the grid. There is no need to wire up the CellMouseClick or SelectionChanged events to keep the controls in sync.
Another consideration is the cmbSehir_SelectionChangeCommitted method that fires every time the user changes the selection in the cmbSehir combo box. In this method, the code queries the data base and sets the combo boxes data source. This is fine, however, are you sure you want to query the database and refill the combo box EVERY time the user changes this selection? I am guessing one query would be sufficient, until new data is added, removed or changed.
The code below sets the DataSource for the combo boxes to the same data source of the DataGridView using different ValueMembers.
DataTable AllData;
private void Form1_Load(object sender, EventArgs e) {
AllData = GetDT();
dataGridView1.DataSource = AllData;
comboBox1.DataSource = AllData;
comboBox2.DataSource = AllData;
comboBox1.ValueMember = "sehir";
comboBox2.ValueMember = "ilceler";
}
Very specific question, I know. I'm not sure how best to word this. Currently, my cell_formatting method will change the color of a cell based on its value:
dataGridView.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.cell_formatting);
....
public void cell_formatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].Name.Equals("LocCode"))
{
if (e.Value.ToString() == "OK")
{
e.CellStyle.BackColor = Color.Red;
}
}
}
What I actually need to do is check a different column index than that of the one I'm changing the color of. There's a column color that will decide what color the LocCode cell will change to.
I imagine there's a way to catch which item in my dataGridView.DataSource is being looked at while inside cell_formatting(), but I don't know how to access it.
I suggest you to use DataTable to get the color value. Here is an simple example for you.
I made a Table and add 3 records in it.
In form_load, data loaded to DataGridView,
DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=serverName;Database=db;Trusted_Connection=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from TestTable", conn);
dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
dataGridView1.DataSource = dt;
}
Then, here we came cell_formatting event,
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("TestName")) // LocCode
{
if (e.Value != null && e.Value.ToString() != "") // Check for extra line
{
string a = dt.Rows[e.RowIndex]["Color"].ToString(); //current row's Color column value.
e.CellStyle.BackColor = Color.FromName(a); // color as backcolor
}
}
}
Output;
Hope helps,
I imagine there's a way to catch which item in my dataGridView.DataSource is being looked at while inside cell_formatting(), but I don't know how to access it.
Sure there is.
First, use the DataGridViewCellFormattingEventArgs.RowIndex property to get the index of the row being formatted. Then use the index to the get the corresponding DataRow object, and finally use the DataGridViewRow.DataBoundItem property to get the corresponding data source object, casting it to the appropriate type:
var item = dataGridView.Rows[e.RowIndex].DataBoundItem as YourDataSourceObjectType;
I am not handy at this. I have a dataGridView bound to SQL by a dataset. All column are generated by the dataset except one column which is replaced by a coded one which is a comboboxColumn.
To avoid new columns being generated while editing a row, I have set the allowUserToAddRows to false. Now I would like to add new empty rows by button click. I have tried in several way without any success.
Updated with full code
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.affitto_saTableAdapter.Fill(this.affitto_SADataSet.affitto_sa);
DataGridViewComboBoxColumn comboCol1 = new DataGridViewComboBoxColumn();
comboCol1.Name = "Periodo Rif.";
List<DateTime> periods = new List<DateTime>() { DateTime.Now.AddMonths(-2), DateTime.Now.AddMonths(-1), DateTime.Now, DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2) };
//Dates = Dates.OrderBy(x => x).ToList();
List<string> colSource = periods.Select(x => x.ToString("MMM/yyyy")).ToList();
comboCol1.DataSource = colSource;
dataGridView1.Columns.Add(comboCol1);
comboCol1.DataPropertyName = "Periodo";
dataGridView1.Columns["Periodo Rif."].DisplayIndex = 1;
}
private void button1_Click(object sender, EventArgs e)
{
/* DataTable dt = dataGridView1.DataSource as DataTable;
DataRow row = dt.NewRow();
dt.Rows.Add(row);*/
(dataGridView1.DataSource as DataTable).Rows.Add((dataGridView1.DataSource as DataTable).NewRow());
}
}
How can I add a new empty row to such DGV?
Here solution for your problem:
dataGridView1.Rows.AddCopy(myDataGridView1.Rows.Count - 1);
Since your DGV not binded with any of dataSource hence AddCopy of DataGridViewRow will add new row at end of DGV (at Rows.Count - 1).
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Rows.Add();
}
I'm using C#, winforms.
Got a small problem. I've debugged as much as possible that leads me to believe the code I'm using is causing the problem.
Ok so I have a combo box that is filled with data from a query.
There are 2 columns "name", and "keycode". I display the name only using:
accCollection.DisplayMember = "name";
Then I use the following to get the keycode value that corresponds to the name.
string acct = accCollection.SelectedValue.ToString();
The problem I have is the keycode does NOT match the name. I though this may be my query so what I did was to display the query results in a data grid view JUST before I fill the comboBox. The data grid view displays the correct results which leads me to believe that I'm using the wrong code!
Hopefully it's a silly one line problem, if you guys want any more code let me know and I will edit this post.
UPDATE heres the code i forgot to mention, as you can see i already have assigned the data member
accCollection.DataSource = myTable;
accCollection.DisplayMember = "name";
accCollection.ValueMember = "keycode";
UPDATE:::: Ok some more info. the selected value should be 1557 which is the names account number. but i get 1855, which is a different account number. like i said the datatable is correct....this is why im sooooooo confused!
UPDATE:: heres some code so you can see how i update the combo box with the info!
SqlCommand accountFill = new SqlCommand("SELECT name, keycode FROM dbo.Customer", conn1);
SqlDataAdapter readacc = new SqlDataAdapter(accountFill);
DataTable dt = new DataTable();
readacc.Fill(dt);
dataGridView3.DataSource = dt;
conn1.Close();
accCollection.DataSource = dt;
accCollection.DisplayMember = "name";
accCollection.ValueMember = "keycode";
then i pass the following into my task that calls my other query.
private void button1_Click_1(object sender, EventArgs e)
{
checkBox1.Checked = true;
string acct = accCollection.SelectedValue.ToString();
Task t = new Task(() => GetsalesFigures(acct));
t.Start();
}
UPDATE:: just to show the data i get!
ok so after some help with debugging, ive used the follwing code to get these resuults.
var result = accCollection.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}
this = 1885 which is wrong
BUT when i do this.
DataRowView row = (DataRowView)accCollection.SelectedItem;
if (row != null)
{
MessageBox.Show(row[0] + " " + row[1]);
}
its shows the correct data, "melksham" "1557"
why is this?
You may use SelectedValue or SelectedItem property but also you have to check whether the returned value is null or not.
If you bind the DataTable then the SelectedItem property return DataRowView.
DataRowView row = (DataRowView)accCollection.SelectedItem;
if(row!=null)
{
MessageBox.Show(row[0] + " " + row[1]);
}
In case of SelectedValue,
var result = accCollection.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}
EDIT:
Code in Form_Load event:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("A1", typeof(int));
dt.Columns.Add("A2");
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "A2";
comboBox1.ValueMember = "A1";
}
Code in Click handler of Button:
var result = comboBox1.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}
DataRowView row = (DataRowView)comboBox1.SelectedItem;
if (row != null)
{
MessageBox.Show(row[0] + " " + row[1]);
}
Several Things:
DisplayMember property should be the name of the column to be displayed inside the combobox.
ValueMember property should be the name of the column which is the value of the item.
accCollection.DisplayMember = "name";
accCollection.ValueMember = "key";
If you want the value of the selected item you should use:
string acct = accCollection.SelectedValue.ToString();
Get the Display text as :
string acct = accCollection.SelectedText;
See this for details .
I have created a DataTable & i used to bind the dataTable to the combobox to display the title types and i wanted to get the title id which is in the datatable to a variable.
cmbTitle.DataSource=dataTable;
cmbTitle.DisplayMember="title_type";
cmbTitle.ValueMember="id";
then on the selection changed event of cmbtitle, i got the selected value member to a string and parsed in into an integer to save it back for the database as it is a foreign key.
private void cmb_title_SelectedIndexChanged(object sender, EventArgs e)
{
string userTitle = cmb_title.SelectedValue.ToString();
int.TryParse(userTitle, out this.userTitle);
MessageBox.Show(this.userTitle.ToString());
}
I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things.
First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice.
I want to see it once. What am I doing wrong?
private void BankFlow_Load(object sender, EventArgs e)
{
initMethod();
dataTable = getBankFlowData(globalConnection);
dataGridView1.DataSource = dataTable;
}
private static DataTable getBankFlowData(OracleConnection oc)
{
DataTable dt = new System.Data.DataTable();
try
{
OracleCommand od = oc.CreateCommand();
od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE";
od.CommandType = System.Data.CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(od);
adapter.Fill(dt);
}
catch (Exception)
{
}
return dt;
}
private static void initMethod()
{
targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString();
Console.WriteLine("Target : {0}", targetSystem);
sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString();
Console.WriteLine("Source : {0}", sourceSystem);
globalConnection.ConnectionString = sourceSystem;
globalConnection.Open();
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.HeaderText = "SELECT";
col.ReadOnly = false;
col.DefaultCellStyle.BackColor = Color.Beige;
dataGridView1.Columns.Add(col);
}
Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.
You need to add the column outside of the databindingcomplete event.
EDIT
Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.