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());
}
Related
i Have A Janus Gridex in Windows Form with Several Columns.
I want to Change the FilterEditType of All Columns in This GridEx to Checklistbox. So User Can Filter each Column Based on one or more than one values.
Please Give me the sample Code in C# or VB.net.
You need to add certain events for this one ,
First of all make the GridEx columns FilterEditType = Custom
Then add the Janus.Windows.GridEX.EditControls.CheckedComboBox for each column FilterEditType. For eg: add this events
private void grdTest_InitCustomEdit(object sender, Janus.Windows.GridEX.InitCustomEditEventArgs e)
{
if (e.Column.Key == "ColumnName")
{
cboTest.Visible = true;
e.EditControl = cboTest;
}
}
private void grdTest_EndCustomEdit(object sender, Janus.Windows.GridEX.EndCustomEditEventArgs e)
{
//this (dtTest) datatable is actually the datasource assigned for the grid
dtTest.DefaultView.RowFilter = string.Empty;
cboTest.Visible = false;
string Filter = string.Empty;
if (cboTest.CheckedItems != null)
{
foreach (GridEXRow row in cboTest.DropDownList.GetCheckedRows())
{
if (Filter != string.Empty)
Filter += " OR ColumnName = '";
else Filter = "( ColumnName = '";
Filter += row.Cells[2].Value;
Filter += "'";
}
Filter += " )";
}
dtTest.DefaultView.RowFilter = Filter;
grdTest.DataSource = dtTest.DefaultView;
}
private void grdTest_ClearFilterButtonClick(object sender, Janus.Windows.GridEX.ColumnActionEventArgs e)
{
if (e.Column.Key == "ColumnName")
cboTest.CheckAll();
grdTest_EndCustomEdit(null, null);
}
Then for the checked combo you need to design with multiple columns as you need, but one column should be a CheckBox and make it ActAsSelector = True,
The above example the checked combo has actually 3 columns , first one checkbox , second one is an ID (primary key ) and the last one is the name. I used the name column to filter the datatable.
In the DropDown event of the combo assign the datasource for it from the GirdEx datasource:
private void cboTest_DropDown(object sender, EventArgs e)
{
int C = 1;
DataRow DR;
DataTable dtComboDS= new DataTable();
dtComboDS.Columns.Add("ID", typeof(int));
dtComboDS.Columns.Add("Name", typeof(string));
var depts = (from x in dtTest.AsEnumerable() select x.Field<string>("ColumnName")).ToList();// dtTest is actually the datasource assigned for the GridEx
foreach (var Row in depts.Distinct().ToList())
{
DR = dtComboDS.NewRow();
DR["ID"] = C++;
DR["Name"] = Row;
dtComboDS.Rows.Add(DR);
}
cboTest.DropDownDataSource = dtComboDS;
}
private void cboTest_CloseUp(object sender, EventArgs e)
{
cboTest.Visible = false;
grdTest.UpdateData();
}
On the closeup event hide the checked combo and update the grid to get the result.
Hope this will help !
Good Luck.
Problem: Cannot retrieve id, name and image from datagrid to its boxes.
I Tried the Code Below how to display id, name and image on its boxes by Select from the dataGrid especially the image which has been save on a database as byte.
private void Personlist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid gd = (DataGrid)sender;
DataRowView row_selected = gd.SelectedItem as DataRowView;
if (row_selected != null)
{
IDtextbox.Text = row_selected["Id"].ToString();
Nametextbox.Text = row_selected["Name"].ToString();
***// i need here to write a row for image.***
}
}
Use the SelectionChangedEventArgs e to retrieve the selected items.
There is a member called 'AddedItems'.
- In case of single-selection this always hold the one currently selected item.
- In case of multi-selection, it holds those items, which were currently added to the DataGrid-selection.
So, your code could look something like this:
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems != null && e.AddedItems.Count > 0)
{
DataRowView row_selected = e.AddedItems[0] as DataRowView;
if (row_selected != null)
{
IDtextbox.Text = row_selected["Id"].ToString();
Nametextbox.Text = row_selected["Name"].ToString();
}
}
}
Is your DataGrid filled with some data at all?
You could use some debug-data in the constructor of your app like
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Pic");
DataRow dr = dt.NewRow();
dr["Id"] = "1";
dr["Name"] = "You";
dr["Pic"] = "0x5234265";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = "2";
dr["Name"] = "Me";
dr["Pic"] = "0x000202";
dt.Rows.Add(dr);
theDataGrid.ItemsSource = dt.DefaultView;
Perhaps you can post a little more code, because I still cannot figure out, what your question actually is about?
And generally, WPF-Binding would be nicer to fill you UI elements with data.
I have 3 comboboxes.
At first I imported the number of stations. Example 11650, 13450 and more.
When the user selects the number from the first combobox After automatically according to the station number in the second combobox After giving the date. Because each station dates are different.
My question to you is how I can do so if the user enters the number keys, in the second combobox to show dates?
My Code is :
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string MyConString1 = "SERVER=localhost;" +
"DATABASE=hydrodb;" +
"UID=root;" +
"PASSWORD=;";
MySqlConnection connection1 = new MySqlConnection(MyConString1);
string command1 = "select Dat FROM hydgod where Station=" + comboBox1.SelectedItem.ToString();
MySqlDataAdapter da1 = new MySqlDataAdapter(command1, connection1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
comboBox2.Items.Clear();
comboBox3.Items.Clear();
comboBox2.SelectedItem = -1;
comboBox3.SelectedItem = -1;
foreach (DataRow row in dt1.Rows)
{
string rowz = string.Format("{0}", row.ItemArray[0]);
comboBox2.Items.Add(rowz);
comboBox3.Items.Add(rowz);
}
connection1.Close();
}
I would suggest to get all corresponding dates into a List<string> and bind it as DataSource to the second ComboBox
List<string> dateList = new List<string>();
foreach (DataRow row in dt1.Rows)
{
dateList.Add(string.Format("{0}", row.ItemArray[0]);
}
comboBox2.DataSource = dateList;
EDIT:
I received the same values result in combobox. 2010-01-01 12:00:00AM
I want to cut the 12:00:00AM
If row.ItemArray[0] is of type DateTime you can try:
dateList.Add(row.ItemArray[0].ToString("yyyy-MM-dd));
if it is a simple string you can split it:
dateList.Add(row.ItemArray[0].Split(' ')[0]);
ps. to populate the 3-rd combobox also you can just hook the same List also to the 3-rd one:
comboBox3.DataSource = dateList;
Don't add the items manually and then hook the list to the DataSource. Do either or
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;
The below is the code which returns correctly in one form,
private void LoadCompanyNames()
{
ds = dataconnector.GetCompanyNames();
dt = ds.Tables[0];
statlbl.Text = "Retrieving Company Details";
cmpycb.DisplayMember = "CompanyName";
cmpycb.ValueMember = "CompanyID";
cmpycb.DataSource = dt;
}
but, in second form when i called it returns system.data.datarowview
code in second form
private void LoadCompanyNames()
{
ds2 = dataconnector.GetCompanyNames();
dt2 = ds.Tables[0];
statlbl.Text = "Retrieving Company Details";
regnamcb.DisplayMember = "CompanyName";
regnamcb.ValueMember = "CompanyID";
regnamcb.DataSource = dt2;
}
Also, i checked the property of both the combobox in both forms, it looks similar.
If anyone knows the cause, thanks for their help.
You get the System.Data.DataRowView as the value because the ComboBox still hasn't been loaded. I suggest put the code in some other events like form_shown.
Also you can check whether the value its loaded by checking selected value like this:
if (combobox.SelectedValue == null ||
combobox.SelectedValue.ToString() == "System.Data.DataRowView")
return;
//Rest of the code