I have a Datagrid (named 'dg') & a Combobox (named 'cmb2') in my c# WPF app. What I'm trying to do is when I select an item from the combobox the app opens a excel file (*.xlsx) in read-only mode and filters the excel data by matching the text of the combobox with first column of the excel file and displays the filtered excel file data in the datagrid.
So, I have implemented a SelectionChanged event in cmb2 as follows :
private void cmb2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
dg.ItemsSource=null;
cmb2.Text="";
int rowno = 0;
string kword = cmb2.Text;
using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(file_Bills), false))
{
ExcelWorksheet workSheet = package.Workbook.Worksheets[0];
for (int i = 2; i <= workSheet.Dimension.End.Row; i++)
{
if (!string.IsNullOrEmpty(workSheet.Cells["A"+i].Text))
{
rowno =i;
}
}
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("Party");
dtTemp.Columns.Add("Bill No.");
dtTemp.Columns.Add("Bill Date");
dtTemp.Columns.Add("Amount");
dtTemp.Columns.Add("Due Date");
dtTemp.Columns.Add("Remarks");
dtTemp.Columns.Add("Payment Released on");
//DataRow drAddItem;
for (int row = 2; row <= rowno; row++)
{
if (workSheet.Cells[row, 1].Text == kword)
{
FilterDGV(dtTemp, workSheet, row);
dtTemp.AcceptChanges();
}
}
dg.ItemsSource=dtTemp.DefaultView;
}
}
Using the below helper method :
public static void FilterDGV(DataTable tbl, ExcelWorksheet sht, int rowIndex)
{
DataRow drAddItem;
var columnMapping = new[]
{
"Party",
"Bill No.",
"Bill Date",
"Amount",
"Due Date",
"Remarks",
"Payment Released on"
};
drAddItem = tbl.NewRow();
tbl.Rows.Add(drAddItem);
var columnIterator = columnMapping.GetEnumerator();
for (int column = 1; column < 9; column++)
{
if (column == 7) continue;
columnIterator.MoveNext();
object columnValue = sht.Cells[rowIndex, column].Text;
drAddItem[columnIterator.Current.ToString()] = columnValue.ToString();
}
//tbl.AcceptChanges();
}
But when I select an item from the combobox, only the headers appear and not the actual data.
Help