How to determine the column name to read value from a list in c# at run time? - winforms

I have a datagridview (DGV) which contains some columns and a generic list which contains the focus information for all those columns available in the DGV. Now when I enter e cell in DGV, I want to get it's focus information from the list in a string variable. I am receiving the DGVs currentCell and fieldName (DGVs column name for which I want to load focus info) as input parameters. Below is my code:
private Rectangle GetFocusSettingsForField(string fieldName, DataGridViewCell currentCell)
{
NA27Bo bo = new NA27Bo();
Rectangle rectangle = new Rectangle();
string projectId = dgvEntryVerify["ProjectId", currentCell.RowIndex].Value.ToString();
string batchId = dgvEntryVerify["BatchId", currentCell.RowIndex].Value.ToString();
string imageId = dgvEntryVerify["ImageId", currentCell.RowIndex].Value.ToString();
string noOnImage = dgvEntryVerify["NumberOnImage", currentCell.RowIndex].Value.ToString();
int serialNo = Convert.ToInt32(dgvEntryVerify["SerialNumber", currentCell.RowIndex].Value.ToString());
PropertyInfo[] properties = bo.GetType().GetProperties();
string actualFieldName = "";
for (int i = 0; i < properties.Length; i++)
{
if (properties[i].Name.Contains(fieldName + "Focus"))
{
actualFieldName = properties[i].Name;
}
}
// Here I want to get the data from property "actualFieldName" of the list
//string value = data from property "actualFieldName" of the list
}
I am using VS2012, C#, Winforms but Framework 2.0 (framework can't be changed).

Related

Export data from excel to a database table using ClosedXML example

i have to read rows of data from an excel file which has only a column and then i have to save the rows in a table in database .
In my project i have to use ClosedXML .dll .
I have search but i couldn't find an example .
Can you please help me?
Thanks
For the ClosedXML part, you can refer to the documentation at https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data
private static void Main()
{
List<String> categories;
List<String> companies;
ExtractCategoriesCompanies("NorthwindData.xlsx", out categories, out companies);
// Do something with the categories and companies
}
private static void ExtractCategoriesCompanies(string northwinddataXlsx, out List<string> categories, out List<string> companies)
{
categories = new List<string>();
const int coCategoryId = 1;
const int coCategoryName = 2;
var wb = new XLWorkbook(northwinddataXlsx);
var ws = wb.Worksheet("Data");
// Look for the first row used
var firstRowUsed = ws.FirstRowUsed();
// Narrow down the row so that it only includes the used part
var categoryRow = firstRowUsed.RowUsed();
// Move to the next row (it now has the titles)
categoryRow = categoryRow.RowBelow();
// Get all categories
while (!categoryRow.Cell(coCategoryId).IsEmpty())
{
String categoryName = categoryRow.Cell(coCategoryName).GetString();
categories.Add(categoryName);
categoryRow = categoryRow.RowBelow();
}
// There are many ways to get the company table.
// Here we're using a straightforward method.
// Another way would be to find the first row in the company table
// by looping while row.IsEmpty()
// First possible address of the company table:
var firstPossibleAddress = ws.Row(categoryRow.RowNumber()).FirstCell().Address;
// Last possible address of the company table:
var lastPossibleAddress = ws.LastCellUsed().Address;
// Get a range with the remainder of the worksheet data (the range used)
var companyRange = ws.Range(firstPossibleAddress, lastPossibleAddress).RangeUsed();
// Treat the range as a table (to be able to use the column names)
var companyTable = companyRange.AsTable();
// Get the list of company names
companies = companyTable.DataRange.Rows()
.Select(companyRow => companyRow.Field("Company Name").GetString())
.ToList();
}
EDIT: The below only gets you a populated datatable. You'll then need to load that datatable into your database. You don't say which database this is, but for SQL Server you would use the SqlBulkCopy class (see definition, which also has an example).
Late to the party, but try this:
public static DataTable GetDataTableFromExcel(string path, string sheetname = "", bool hasHeader = true)
{
using (var workbook = new XLWorkbook(path))
{
IXLWorksheet worksheet;
if (string.IsNullOrEmpty(sheetname))
worksheet = workbook.Worksheets.First();
else
worksheet = workbook.Worksheets.FirstOrDefault(x => x.Name == sheetname);
var rangeRowFirst = worksheet.FirstRowUsed().RowNumber();
var rangeRowLast = worksheet.LastRowUsed().RowNumber();
var rangeColFirst = worksheet.FirstColumnUsed().ColumnNumber();
var rangeColLast = worksheet.LastColumnUsed().ColumnNumber();
DataTable tbl = new DataTable();
for (int col = rangeColFirst; col <= rangeColLast; col++)
tbl.Columns.Add(hasHeader ? worksheet.FirstRowUsed().Cell(col).Value.ToString() : $"Column {col}");
Logger("started creating datatable");
rangeRowFirst = rangeRowFirst + (hasHeader ? 1 : 0);
var colCount = rangeColLast - rangeColFirst;
for (int rowNum = rangeRowFirst; rowNum <= rangeRowLast; rowNum++)
{
List<string> colValues = new List<string>();
for (int col = 1; col <= colCount; col++)
{
colValues.Add(worksheet.Row(rowNum).Cell(col).Value.ToString());
}
tbl.Rows.Add(colValues.ToArray());
}
Logger("finished creating datatable");
return tbl;
}
}
and call like this:
var datatable = GetDataTableFromExcel(fileName, sheetName);
If you're using (the excellent and free in its basic form) LinqPad, you can inspect the datatable using datatable.Dump();

How do I set values for the entries in a Windows Forms ComboBox?

I want to have a drop down list with 12 choices.
I found that ComboBox is what I need (if there is a better control kindly tell me).
I dragged and drop a combo box into a panel using VS2012 and then clicked on the left arrow that appears on the combo box. The following wizard shows:
As you can see, I am just able to type the name of the choice but not the value of it.
My question is how to get the value of these choices?
What I have tried
I built an array with the same length as the choices, so when the user selects any choice, I get the position of that choice and get the value from that array.
Is there a better way?
You need to use a datatable and then select the value from that.
eg)
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Description", typeof(string));
dt.Load(reader);
//Setting Values
combobox.ValueMember = "ID";
combobox.DisplayMember = "Description";
combobox.SelectedValue = "ID";
combobox.DataSource = dt;
You can then populate your datatable using:
dt.Rows.Add("1","ComboxDisplay");
Here, the DisplayMember(The dropdown list items) are the Descriptions and the Value is the ID.
You need to include a 'SelectedIndexChanged' Event on your combobox (If using VS then double click the control in Design Mode) to get the new values. Something like:
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
int ID = Combobox.ValueMember;
string Description = ComboBox.DisplayMember.ToString();
}
You can then use the variables in the rest of your code.
You cannot use the wizard to store values and text. To store DisplayText/Value pair the combobox needs to be connected to some data.
public class ComboboxItem
{
public string DisplayText { get; set; }
public int Value { get; set; }
}
There are two properties on the combobox - DisplayMember and ValueMember. We use these to tell the combobox that - show whats in DisplayMember and the actual value is in ValueMember.
private void DataBind()
{
comboBox1.DisplayMember = "DisplayText";
comboBox1.ValueMember = "Value";
ComboboxItem item = new ComboboxItem();
item.DisplayText = "Item1";
item.Value = 1;
comboBox1.Items.Add(item);
}
To get the value -
int selectedValue = (int)comboBox1.SelectedValue;

GTK CellRendererCombo set value into appropriate cell

What I'm trying to do it a TreeView that have several columns. The first column is a ComboBox, which means that I use Gtk.CellRendererCombo. The thing is, when I selected a value from the ComboBox, I'd like the Text from the cell to change from "" to the value I just selected. It feasible if at the Gtk.CellRendererCombo.Edited event I set the columns Text field to the EditedArgs.NewText.
The problem is, each time I set a value, I create a new row, and I'd like the Text Field to act like it does in the Gtk.CellRendererText, but it doesn't. It's not a different value for each row at that column, but the same value as setted in the Gtk.CellRendererCombo.Text
The Gtk.CellRenderer should not contain any state, so OK, using the Text field is a really bad idea from what I'm trying to do.
But if I set some value from the Gtk.ListStore that is the Model of my TreeView (Which is different from the Model for the Gtk.CellRendererCombo). The values setted will never show at the Column of the ComboBox.
class Program
{
private static Gtk.TreeView treeview = null;
static void OnEdited(object sender, Gtk.EditedArgs args)
{
Gtk.TreeSelection selection = treeview.Selection;
Gtk.TreeIter iter;
selection.GetSelected(out iter);
treeview.Model.SetValue(iter, 0, args.NewText); // the CellRendererCombo
treeview.Model.SetValue(iter, 1, args.NewText); // the CellRendererText
//(sender as Gtk.CellRendererCombo).Text = args.NewText; // Will set all the Cells of this Column to the Selection's Text
}
static void Main(string[] args)
{
Gtk.Application.Init();
Gtk.Window window = new Window("TreeView ComboTest");
window.WidthRequest = 200;
window.HeightRequest = 150;
Gtk.ListStore treeModel = new ListStore(typeof(string), typeof(string));
treeview = new TreeView(treeModel);
// Values to be chosen in the ComboBox
Gtk.ListStore comboModel = new ListStore(typeof(string));
Gtk.ComboBox comboBox = new ComboBox(comboModel);
comboBox.AppendText("<Please select>");
comboBox.AppendText("A");
comboBox.AppendText("B");
comboBox.AppendText("C");
comboBox.Active = 0;
Gtk.TreeViewColumn comboCol = new TreeViewColumn();
Gtk.CellRendererCombo comboCell = new CellRendererCombo();
comboCol.Title = "Combo Column";
comboCol.PackStart(comboCell, true);
comboCell.Editable = true;
comboCell.Edited += OnEdited;
comboCell.TextColumn = 0;
comboCell.Text = comboBox.ActiveText;
comboCell.Model = comboModel;
comboCell.WidthChars = 20;
Gtk.TreeViewColumn valueCol = new TreeViewColumn();
Gtk.CellRendererText valueCell = new CellRendererText();
valueCol.Title = "Value";
valueCol.PackStart(valueCell, true);
valueCol.AddAttribute(valueCell, "text", 1);
treeview.AppendColumn(comboCol);
treeview.AppendColumn(valueCol);
// Append the values used for the tests
treeModel.AppendValues("comboBox1", string.Empty); // the string value setted for the first column does not appear.
treeModel.AppendValues("comboBox2", string.Empty);
treeModel.AppendValues("comboBox3", string.Empty);
window.Add(treeview);
window.ShowAll();
Gtk.Application.Run();
}
}
I'd like the Cell of the ComboBox in which the selection has been made to show the value, but continue to be editable for later changes.
If someone has a way of doing this, I would be very grateful for you input. thanks.
Update:
What I think, because Gtk.CellRendererCombo inherits from Gtk.CellRendererText it just ignores the value setted in the cell. Now, I guess I could create a custom MyCellRendererCombo that inherits from Gtk.CellRendererCombo and use the value setted in the cell when supplied for the rendering, but the documentation on the difference between Gtk.CellRendererText and Gtk.CellRendererCombo is quite slim... I guess I should visit the implementation in C to know the details.
Ok, I've found a solution to my problem, I use a "hidden" column in which I read the "text" value. The hidden column contains the Gtk.CellRendererText, the Gtk.CellRendererCombo must have an Attribute Mapping with the new Column.
The resulting code is below:
class Program
{
private static Gtk.TreeView treeview = null;
static void OnEdited(object sender, Gtk.EditedArgs args)
{
Gtk.TreeSelection selection = treeview.Selection;
Gtk.TreeIter iter;
selection.GetSelected(out iter);
treeview.Model.SetValue(iter, 1, args.NewText); // the CellRendererText
}
static void Main(string[] args)
{
Gtk.Application.Init();
Gtk.Window window = new Window("TreeView ComboTest");
window.WidthRequest = 200;
window.HeightRequest = 150;
Gtk.ListStore treeModel = new ListStore(typeof(string), typeof(string));
treeview = new TreeView(treeModel);
// Values to be chosen in the ComboBox
Gtk.ListStore comboModel = new ListStore(typeof(string));
Gtk.ComboBox comboBox = new ComboBox(comboModel);
comboBox.AppendText("<Please select>");
comboBox.AppendText("A");
comboBox.AppendText("B");
comboBox.AppendText("C");
comboBox.Active = 0;
Gtk.TreeViewColumn comboCol = new TreeViewColumn();
Gtk.CellRendererCombo comboCell = new CellRendererCombo();
comboCol.Title = "Combo Column";
comboCol.PackStart(comboCell, true);
comboCol.AddAttribute(comboCell, "text", 1);
comboCell.Editable = true;
comboCell.Edited += OnEdited;
comboCell.TextColumn = 0;
comboCell.Text = comboBox.ActiveText;
comboCell.Model = comboModel;
comboCell.WidthChars = 20;
Gtk.TreeViewColumn valueCol = new TreeViewColumn();
Gtk.CellRendererText valueCell = new CellRendererText();
valueCol.Title = "Value";
valueCol.PackStart(valueCell, true);
valueCol.AddAttribute(valueCell, "text", 1);
valueCol.Visible = false;
treeview.AppendColumn(comboCol);
treeview.AppendColumn(valueCol);
// Append the values used for the tests
treeModel.AppendValues("comboBox1", "<Please select>"); // the string value setted for the first column does not appear.
treeModel.AppendValues("comboBox2", "<Please select>");
treeModel.AppendValues("comboBox3", "<Please select>");
window.Add(treeview);
window.ShowAll();
Gtk.Application.Run();
}
}

DataSet created in code not Binding to ListView

I have a WPF User Control with a ListView in it that is created based on the DataSet that is passed to it:
public void PopulateList(DataSet ds) {
listView.View = CreateGridViewColumns(ds.Tables[0]);
listData.DataContext = ds.Tables[0];
}
private GridView CreateGridViewColumns(DataTable dt) {
// Create the GridView
var gv = new GridView {AllowsColumnReorder = true};
// Create the GridView Columns
foreach (DataColumn item in dt.Columns) {
var gvc = new GridViewColumn
{
DisplayMemberBinding = new Binding(item.ColumnName),
Header = item.ColumnName,
Width = Double.NaN
};
gv.Columns.Add(gvc);
}
return gv;
}
Now I create the user control in code and call it's PopulateList with the appropriate dataset and this is where the problems are starting:
If I pass in a dataset that was created from a call to the database the list view shows all the data but if i pass in a DataSet that i created in code the ListView shows the Columns but will not show the data
//This is a function that hides the DB call return type is DataSet
var dsPatientSmokingStatusHistory = DataRepository.PatientSmokingStatusProvider.GetHistory(PatientId);
//radGridViewPatientSmokingStatus.DataSource = dsPatientSmokingStatusHistory.Tables[0];
var dt = new DataTable();
string c1 = "Date".PadLeft(23).PadRight(23);
string c2 = "Status".PadLeft(20).PadRight(50);
dt.Columns.Add(c1);
dt.Columns.Add(c2);
int i = 0;
foreach (DataRow row in dsPatientSmokingStatusHistory.Tables[0].Rows) {
var dataRow = dt.NewRow();
dataRow[c1] = ((DateTime)row["Date"]).ToString("MM/dd/yyyy");
dataRow[c2] = row["Status"].ToString();
dt.Rows.Add(dataRow);
dt.Rows[i].AcceptChanges();
i++;
}
DataSet ds = new DataSet();
dt.TableName = "Table";
ds.Tables.Add(dt);
ds.AcceptChanges();
smokingStatusGrid.GridWidth = 455;
smokingStatusGrid.GridHight = 97;
//This line does not show data
smokingStatusGrid.PopulateGrid(ds);
//This line will show data
smokingStatusGrid.PopulateGrid(dsPatientSmokingStatusHistory);
Is there a difference between these two datasets that i don't know about that is preventing me from databinding to it?
Also the user control is being used as an ElementHost in a WinForms application (not sure if this makes a difference)
Your code says:
DisplayMemberBinding = new Binding(item.ColumnName)
This binding constructor takes a string paramter which as per MSDN is "The initial Path for the binding" and is of datatype System.Windows.PropertyPath. I guess, since system tries to find a property with the same name in your class, and your string (item.ColumnName) has spaces at start, it runs into a problem (properties can't start with a space).
Would recommend you to take off the padding that you are doing in column name of your table. Apply any padding/margins in the Header of your GridView.

Databinding of DataGridViewComboBoxColumn

In the code below, the combo box named "ConnectionType" shows the selected item, but one cannot change the selected item (it seems like there is only one item in the combo box). If I comment out the line
typeCol.DataPropertyName = "ConnectionTypeName";
then the combo box is selectable, but the correct item is not selected, of course. What am I doing wrong??
Thanks.
private void LoadConnectionsGrid()
{
_dc = new EnterpriseEntities();
dataGridViewConnections.AutoGenerateColumns = false;
dataGridViewConnections.DataSource = _dc.Connection.Include("ConnectionType");
DataGridViewComboBoxColumn typeCol =
(DataGridViewComboBoxColumn)dataGridViewConnections.Columns["ConnectionType"];
typeCol.DataPropertyName = "ConnectionTypeName";
var qry = from c in _dc.ConnectionType
select c.Type;
typeCol.DataSource = qry;
DataGridViewTextBoxColumn nameCol =
(DataGridViewTextBoxColumn)dataGridViewConnections.Columns["ConnectionName"];
nameCol.DataPropertyName = "Name";
DataGridViewTextBoxColumn connStrCol =
(DataGridViewTextBoxColumn)dataGridViewConnections.Columns["ConnectionString"];
connStrCol.DataPropertyName = "ConnectionString";
}
Ultimately, I could not get data binding, the entity framework, and comboboxes to play nice and I just created the data grid brute force (code below). This means that I handle inserts, updates and deletes by hand.
private void LoadConnectionsGrid()
{
DataGridViewComboBoxColumn typeCol =
(DataGridViewComboBoxColumn)dataGridViewConnections.Columns["ConnectionType"];
var qry = from c in _dc.ConnectionType
select c.Type;
typeCol.DataSource = qry;
dataGridViewConnections.Rows.Clear();
foreach (Connection conn in _dc.Connection.Include("ConnectionType"))
{
dataGridViewConnections.Rows.Add(conn.Name,
conn.ConnectionType.Type, conn.ConnectionString);
}
}

Resources