Reputation: 731
I have created a listbox that displays all values that I want to use as a filter for my datagridview.
So this is the listbox I want the selected value from this to be used as a controler/parameter to filter the values shown in
Upvotes: 0
Views: 864
Reputation: 1659
After a conversation with the asker, the final solution is below. Needed to handle the listbox's SelectedIndexChanged event and within that event give the DataGridView a filter.
public partial class CompanyForm : Form
{
private DataTable dataEmployeesSource = new DataTable();
public CompanyForm()
{
InitializeComponent();
initDataEmployees();
initCompanyList();
companyList.SelectedIndexChanged += listbox1_SelectedIndexChanged;
}
private void initDataEmployees()
{
const string sql = "Select fname, ename, c.companyName AS companyName FROM dbo.Users u inner join dbo.Company c on c.companyName = u.company;";
dataEmployeesSource = selectIntoDataTable(sql);
dataEmployees.DataSource = dataEmployeesSource;
}
private void initCompanyList()
{
const string sql = "Select companyName from dbo.Company";
try
{
DataTable dt = selectIntoDataTable(sql);
companyList.DataSource = dt;
companyList.ValueMember = "companyName";
}
catch (Exception ex)
{
MessageBox.Show("There are no companies to display");
}
}
private DataTable selectIntoDataTable(string sql)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cs))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(dt);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
con.Close();
}
}
return dt;
}
private void listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView selectedRow = (DataRowView)companyList.SelectedItem;
string selectedText = (string)selectedRow.Row["companyName"];
DataView dv = dataEmployeesSource.DefaultView;
string columnName = dataEmployeesSource.Columns[2].ColumnName;
string filter = string.Format("{0} = '{1}'", columnName, selectedText);
dv.RowFilter = filter;
dataEmployees.DataSource = dv;
}
}
Upvotes: 1
Reputation: 11480
You would need to enumerate over each item within your control. For the ListBox
the code would be:
foreach(var item in example.Items)
{
// This will expose the internal data, via item now.
}
However, I believe the exact functionality you want, would be:
var item = example.SelectedItem;
This would provide you with the selected information. You may require to anchor to the ListBox
event: SelectedIndexChanged
. This way you could pass a numeric representation to a global to utilize or another approach.
Upvotes: 1