There is a strange behavior when using a ComboBox in VGridControl.
I have a list of objects:
var samples = new List<Samples>();
samples.Add(new Samples {Id = 1, Name = "s1"});
samples.Add(new Samples {Id = 2, Name = "s2"});
samples.Add(new Samples {Id = 3, Name = "s3"});
samples.Add(new Samples {Id = 4, Name = "s4"});
VGridControl has one row, and this row has a RowEdit = CheckedComboBoxEdit.
CheckedComboBoxEdit.ShowDropDown is set to "DoubleClick".
Then:
repositoryItemCheckedComboBoxEdit1.DataSource = samples;
repositoryItemCheckedComboBoxEdit1.ValueMember = "Id";
repositoryItemCheckedComboBoxEdit1.DisplayMember = "Name";
row.Properties.Value = "2, 4";
Repro steps:
When I press the drop down button and then check the CheckedState for each item - it's OK. It shows the correct values;
When I simply select the row (press the row itself) and do not expand the drop down list, then CheckedState of all items is "Unchecked".
I check using:
int checkedItems = 0;
foreach (var item in repositoryItemCheckedComboBoxEdit1.GetItems().Cast<CheckedListBoxItem>())
{
if (item.CheckState == CheckState.Checked)
{
checkedItems++;
}
}
So, how to get the checked values from CheckedComboBoxEdit?
I found a simple answer. In order to get row value, you can use:
var s = vGridControl.GetCellValue(row1, vGridControl.FocusedRecord).ToString();
This shows a stored value for a row. Then you can convert it into the list:
var list = s.Split(',').ToList();
Related
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();
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).
I Have a Grid (BrkGrid) in ViewMode... I Add dynamic Check Box (brkChkBox) depending on some logic. A foreach is responsible for adding check boxes to a specific row and column of this grid.. But it takes time while adding check boxes to the BrkGrid.. When I Comment the Add Statement (BrkGrid.Children.Add(brkChkBox)) then the code executes faster.. Any help will be highly appreciated...
CheckBox brkChkBox = null;
foreach (var s in this.ViewData.PlnDtShiftBrksDateList)
{
brkChkBox = new CheckBox
{
DataContext = s,
Tag = s.BreakID,
Width = 20,
VerticalAlignment = VerticalAlignment.Top,
};
Binding chkBoxBinding = new Binding("IsSelected");
chkBoxBinding.Source = s;
chkBoxBinding.Mode = BindingMode.TwoWay;
brkChkBox.SetBinding(CheckBox.IsCheckedProperty, chkBoxBinding);
brkChkBox.Click += brkChkBox_Click;
Grid.SetColumn(brkChkBox, gridColDic.FirstOrDefault(x => x.Key == s.BreakID).Value);
Grid.SetRow(brkChkBox, gridRowDic.FirstOrDefault(x => x.Key.Date == s.Date.Date).Value);
BrkGrid.Children.Add(brkChkBox);
}
I have a RIA service that is to return a list of schools and populate a datagrid. This datagrid is duplicating the first result throughout the entire grid, as opposed to showing each item from source in its own row.
The service is as follows
var schools1 = (from i in DataContext.PrevSchools
join skl in DataContext.SchoolLists on i.School_id equals skl.School_Id
where i.Email_Address == email
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl.School_name
}).Union(from i in DataContext.PrevSchools
join skl1 in DataContext.Schools on i.School_id equals skl1.School_id
where i.Email_Address == email && i.School_type_id == 1
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl1.School_name
}).OrderBy(q => q.SchoolName);
return schools1;
The Databinding is:
this.PrevSchools.prevSchoolDataGrid.DataContext = SchoolsList;
The SchoolList is an ObservableCollection, it was set as a list and also a, IEnumerable, and it still yielded the duplicated results.
Fixed it, it was an error in the Model class, the key was set to the wrong property
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);
}
}