ListBox.DataBinding Method Question - c#

Question about the ListBox.DataBinding method. I'm loading a listbox with a DataRows array object and I want to check for each DataRow element a column value if its true/false. If the column value is true, then modify the style for the current listBox.ListItem object. Below is some sample code.:
System.Data.DataRow[] rows = Data.SchoolDetails.Select(filter);
lstBox.DataBinding += new EventHandler(lstBox_DataBinding);
lstBox.DataSource = rows;
lstBox.DataTExtField = "Value";
lstBox.DataValueField = "ValueCode";
lstBox.DataBind();
static void lstBox_DataBinding(object sender, EventArgs e)
{
ListBox l = (ListBox) sender;
}

You can't really do that with a ListBox. Maybe you should use ListView, which supports an ItemDataBinding event for each item.

The best answer is probably the one you included in the comment above.
As an alternative I can just loop through the DataRow array and do it that way, and set the style by doing this: lstBox.Items.Add(new ListItem("").Attributes.CssStyle.Add(HtmlTextWriterStyle.FontWeight, "Bold"));. Thanks for hte help. – Brandon Michael Hunter
That is exactly how I'd do it.

Related

DataGridViewComboBoxColumn Selected Value / Index

I am attempting to populate a DataGridViewComboBoxColumn with a list of strings then select one of them based upon their value on form load.
A simple task one would think, but I just can't get it right.
I am populating a DataGridViewComboBoxColumn with strings as such without a problem:
ComboBoxColumn.Items.AddRange("Mr.", "Ms.", "Mrs.", "Dr.");
I also seem to be able to add it to the DataGridView without a problem (This is incorrect see Edit):
ExampleDataGrid.Rows.Add("", ComboBoxColumn, 1000, "");
Now I want to set "Mr." to be selected on load. Other posts suggest that I should be able to simply use:
ExampleDataGrid.Rows[i].Cells["ExampleColumnName"].Value = "Mr.";
But whenever I use it, I get an error that tells me the value is not valid.
Is there something I'm missing?
I can however use this to get the set value without issue:
string Title = ExampleDataGrid.Rows[i].Cells["ExampleColumnName"].Value;
I had a look at the documentation but it doesn't seem to mention how to actually use .Value in this context.
Microsoft Docs
Any thoughts on where I am going wrong would be great.
Edit:
The issue I was having was caused by me setting the ComboBoxItems in the
"ExampleDataGrid.Rows.Add()". This should actually contain the value you want to set. e.g.
ExampleDataGrid.Rows.Add("", "Mr.", 1000, "");
You can initialize the DataGridView this way:
private void Form1_Load(object sender, EventArgs e)
{
var textBoxColumn = new DataGridViewTextBoxColumn();
textBoxColumn.Name = "textBoxColumn";
var comboBoxColumn = new DataGridViewComboBoxColumn();
comboBoxColumn.Items.AddRange("A", "B", "C");
comboBoxColumn.Name = "comboBoxColumn";
dataGridView1.Columns.Add(textBoxColumn);
dataGridView1.Columns.Add(comboBoxColumn);
dataGridView1.Rows.Add("1", "A");
dataGridView1.Rows.Add("2", "B");
}
And then update the value of the comboBoxColumn for the second row this way:
private void button1_Click(object sender, EventArgs e)
{
//You can use either of the following ways:
dataGridView1[1, 1].Value = "C";
//dataGridView1["comboBoxColumn", 1].Value = "C";
//dataGridView1.Rows[1].Cells["comboBoxColumn"].Value = "C";
//dataGridView1.Rows[1].Cells[1].Value = "C";
}
The value which you set for the cell, should be between the values which you added to Items of the DataGridViewComboBoxColumn.

Combobox returns null when value is typed

Sorry if it has some obvious solution, but I am trying to solve it for hours but could not find a solution.
I use several ComboBoxes in my WindowsFormsApplication to relate ids with names. The problem is that when a user select an item from the combobox list, it works fine, but when he types an item, the SelectedValue property of the combobox is null.
To simulate the problem, I created a from with one button and a combobox.
In my actual application, I populate the comboboxes with data from tables in a sqlserver database, but for simplicity, here I populate it with a list:
public Form1()
{
InitializeComponent();
List<KeyValuePair<short,short>> l = new List<KeyValuePair<short,short>>();
l.Add(new KeyValuePair<short,short>(1,10));
l.Add(new KeyValuePair<short,short>(2,20));
l.Add(new KeyValuePair<short,short>(3,30));
this.comboBox1.DataSource = l;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";
}
private void button1_Click(object sender, EventArgs e)
{
if (this.comboBox1.SelectedValue == null)
MessageBox.Show("NULL");
else
MessageBox.Show(this.comboBox1.SelectedValue.ToString());
}
For example, when user select the second item (20) from the list and clicks on the button, messagebox shows 2 as it is expected, but if he types the number 20 into the combobox, the SelectedValue is null.
This problem could be solved by changing the style of combobox:
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
But it prevents user to type into the combobox, so I am forced to use the default ComboBoxStyle.DropDown.
Thats because the combo box does not select the item that you have typed. Add this option
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
Then it will select the item when ever it was able to find it.
By default it is set to AutoCompleteMode.None.
(I think) This is mainly designed for suggestions but it can solve your problem here. also if you want to show the suggestions:
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
by default it is set to AutoCompleteSource.None.
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.autocompletemode%28v=vs.110%29.aspx
An option that you have is using the EventHandler on the comboBox1.TextChange event that will allow you to personally handle how the text is translated into the different options.
This can be added to the designer (similar to a button).
this.comboBox1.TextChanged += new System.EventHandler(this.UpdateValue);
Then depending on how want to read the results and see if you have a match you can create a converter, use another key/value, or you can do a boring old tryparse as I will show you. You will need the list as a property that you can reference to see if you have found the proper results.
private void UpdateValue(object sender, EventArgs e)
{
short result;
if (short.TryParse(comboBox1.Text, out result))
{
var matches = from val in l where val.Value == result select val.Key;
{
foreach (short m in matches)
this.comboBox1.SelectedValue = m;
}
}
}
Good luck! Let me know if you need more examples with the event handler. Don't forget to vote.

combobox returning null value in c#

Here I created a for loop to list a range of numbers from 1 to 30 in the comboBox, but when I try to display the selected item from the combobox into a MessageBox it returns a null value. How can I get it to return the number selected from the comboBox? Here is my code:
string selectedNumber;
public Form1()
{
InitializeComponent();
for (int i = 1; i <= 30; i++)
{
string[] numbers= { i.ToString() };
comboBox1.Items.AddRange(numbers);
}
selectedNumber = comboBox1.SelectedText;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(selectedNumber);
}
}
Reason is clear that you have no text selected
You've to select any item in combobox first. To do so try any of the following
Set SelectedIndex to some valid index
Set SelectedItem to a valid item in combobox through code
Select an item in combobox by clicking it
Then use following code
MessageBox.Show(comboBox1.SelectedText); or
if(comboBox1.SelectedItem != null)//check for null since `SelectedItem` can be null when nothing selected
MessageBox.Show(comboBox1.SelectedItem.ToString());
Note: As #tim pointed in comments SelectedText approach won't work when DropDownStyle set to DropDownList. In that case you've to use SelectedItem approach
Here, with null check:
private void button1_Click(object sender, EventArgs e)
{
var selectedItem = comboBox1.SelectedItem ?? "";
MessageBox.Show(selectedItem.ToString());
}
As several have pointed out, there is nothing selected in the ComboBox when you assign SelectedText to selectedNumber. I would try two things:
First, don't call AddRange every time through the loop - build the array in the loop and then once the loop exits you can use AddRange. I would also use a List<string>:
List<string> numbers = new List<string>();
for (int i = 1; i <= 30; i++)
{
numbers.Add(i.ToString());
}
comboBox1.AddRange(numbers);
Secondly, in your button click event, show the selected text:
MessageBox.Show(comboBox1.SelectedText);
If comBox1's DropDownStyle is set to DropDownList, SelectedText will give an empty string. In that case, something like this might help:
MessageBox.Show(comboBox1.SelectedItem.ToString());
In reality, you'd probably want to handle the corresponding selection changed event for ComboBox as you'd probably want to do something with it in your program, but it looks like you're just trying some things out right now.
Edited To Add
Note that as Sriram said, SelectedItem can be null, so you'll want to check for that condition with either Sriram's or Przemyslaw's code if you're using SelectedItem instead of SelectedText.
Or, you can try this
for (int x = 0; x <= 30; x++)
comboBox1.Items.Add(x.ToString());
I find it a lot simpler

Default load in combobox

If I want to load for example a default country when the combobox shows up ("Country: Lebanon"), how do I do so?
I am using VS2008 (C#). Thank you.
Add some items to the Combobox...it is just a sample, you can run a loop also to add items.
combobox1.Items.Add("USA");
combobox1.Items.Add("England");
combobox1.Items.Add("Kenya");
combobox1.Items.Add("South Africa");
Now your Combobox has four items. To select a specific country try this:
combobox1.Text = "USA";
To select a on the index basis, try this:
combobox1.SelectedIndex = 0; // For USA
Hope it helps.
You can use another method to add items in comboBox:
comboBox1.Items.Insert(0, "Egypt");
//the first item is the item index and the second is the item object.
You would usually just set myCombo.SelectedValue = "Whatever value" as soon as the form is loaded.
Use one of SelectedValue, SelectedIndex, SelectedItem or SelectedText properties of the ComboBox control.
You could try this:
myCombo.SelectedIndex = lebanonsIndex;
You can set it by using IndexOf in the Items collection
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("Lebanon");// case sensitive
This could work. Copy this code in your app.config file within appsettings.
< add key="DefaultCountry" value="Lebanon" />
and copy this at ur win form where you want to view it.
combobox1.Text = System.Configuration.ConfigurationManager.AppSettings["DefaultCountry"].ToString();.<add key="DefaultCountry" value="Lebanon"/>
You can set selected index in Form load event
If Lebanon is first in comboboxItem selectedIndex = 0;
Example:
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0;
}

How do I get the selected row data from a data grid view using SelectedRows?

I have a table that I am displaying in a data grid view control. The user selects a single row from the control and presses a button. I need to retrieve the cells from that row and store them as strings.
Exactly how do I get the data using the SelectedRow method? I've been working on this for several hours and I'm at the end of my rope. Here's an example of something I've tried:
DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells;
If I try to access selRowData[x], the return value does not contain my data.
You're close - you need to reference each Cell through its index and return its Value property:
string firstCellValue = dataGridView1.SelectedRows[0].Cells[0].Value;
string secondCellValue = dataGridView1.SelectedRows[0].Cells[1].Value;
etc.
If you want the data and the data is likely bound to an datasource, then might I suggest that you get the key from the selection, and then you can use that to access the data any way you like:
dataGridView.SelectedDataKey.Value;
Try using the Item element of the dgv.
dgvFoo.Item(0, dgvFoo.CurrentRow.Index).Value
That would return the value of the first item. You could put that into a for loop to get them all.
Another option would be to use the SelectedRows collection on the object and iterate through each selected row (or just the one in your case).
Well there is no datagridview Item property..#Jay Riggs solution is better...Following solution also works:
string firstCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString();
string secondCellValue = dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString();
Here 0 is the first column and dataGridView1.CurrentRow.Index is the current Row from where to get value.
Perhaps this is a more suitable solution use the cell values of the row clicked:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
}
}

Categories