The following code will show the last record in the textboxes. I want to be able to choose which row data to display
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["item_ID"].ToString());
Item.SubItems.Add(reader["item_Desc"].ToString());
listView1.Items.Add(item);
if(action == "add")
{
txtitemid.Text = "";
txtitem.Text = "";
}
else
{
//this is the part i am taking about
txtitemid.Text = reader.GetValue(0).ToString();
txtitemdesc.Text = reader.GetValue(1).ToString();
}
}
Suppose the last record in the table has an item_ID of 15 and item_Desc is dress then the textboxes will show the following according to code above
txtitemid.Text = 15;
txtitemdesc.Text = "dress";
I want to be able to determine which Item_ID details get displayed in the textboxes
Assign the text box values after your while loop:
if (listView1.Items.Count > 0)
{
var displayedItem = listView1.Items[listView1.Items.Count - 1];
txtitemid.Text = displayedItem.SubItems[0].Text;
txtitemdesc.Text = displayedItem.SubItems[1].Text;
}
else
{
txtitemid.Text = "";
txtitemdesc.Text = "";
}
EDIT:
Similarly, you could display the first item by changing the line in the code above to:
var displayedItem = listView1.Items[0];
if (reader.Read())
{
var readMore = true;
while (readMore)
{
var val = reader.GetValue(0).ToString();
readMore = reader.Read();
if (!readMore)
{
//Last record. Use val .
txtitemid.Text = val;
}
else
{
//Not last record. Process val differently.
}
}
}
Related
I am taking an excel file to read the fields and pass it to a class, to be able to enter the DB, when I pass dt.AsEnumerable, it is giving me an error in the "Linea" field. This cell sometimes comes with the $ sign. I think that is what is generating the error, so i am trying to replace the character and then convert it to int, since it is an amount field.
using (var streamExcel = System.IO.File.Create(combineFilePath))
{
await file.CopyToAsync(streamExcel);
}
using (var excelWorkbook = new XLWorkbook(combineFilePath))
{
IXLWorksheet workSheet = excelWorkbook.Worksheet(2);
workSheet.Clear(XLClearOptions.AllFormats);
DataTable dt = new DataTable();
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//for row number check
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
firstRow = false;
}
else
{
//Add rows to DataTable.
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells(1, 50))
{
if (cell.Address.ColumnNumber == 11)
{
workSheet.Cell(11, 11).Style.NumberFormat.Format = "#,##0";
cell.SetDataType(XLDataType.Number);
}
dt.Rows[dt.Rows.Count - 1][i] = cell.CachedValue.ToString();
i++;
}
}
}
try
{
var companys = dt.AsEnumerable().Select(row => new Company
{
Name = row.Field<string>("Nombre"),
Rut = row.Field<string>("Rut"),
Address = row.Field<string>("Dirección"),
AddressNumber = row.Field<string>(#"Nº"),
Location = row.Field<string>("Comuna"),
Region = row.Field<string>("Región"),
Giro = row.Field<string>("Giro Cliente"),
Linea = Convert.ToInt32(row.Field<string>("Monto línea Aprobada").Trim().TrimEnd().Replace(#"$", "")),
Observations = row.Field<string>("Observaciones Comité"),
}).ToList();
UserId = _companyService.AddList(companys);
}
catch (Exception e)
{
}
To visualize where it's failing, you could do something like this:
try{
var companysB = dt.AsEnumerable().Select(row => new
{
Name = row.Field<string>("Nombre"),
LineaRaw = row.Field<string>("Monto línea Aprobada"),
LineaProcessed = row.Field<string>("Monto línea Aprobada").Trim().TrimEnd().Replace(#"$", ""),
})
.ToList();
}
Put a breakpoint on 'companysB' and inspect after it's filled. One or more of the LineaRaw / LineaProcessed will not be a number.
The error was when the "Monto línea Aprobada" cell had a blank value, I did this:
var n = 0;
string cellEmty = "";
foreach (DataRow rowEmpty in dt.Rows)
{
cellEmty = rowEmpty["Monto línea Aprobada"].ToString();
if (string.IsNullOrEmpty(cellEmty))
{
cellEmty = "0";
dt.Rows[n].SetField("Monto línea Aprobada", cellEmty);
}
n++;
}
i have a problem that i change selected index in listview it works fine when i change first time but when i change second time it says "InvalidArgument=Value of '0' is not valid for 'index'."
the code is this ;
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
strpath is way to desktop
try
{
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
}
catch
{
}
i just fixed it like this
I have over 200,000 records in c# Winforms gridview, it takes around an hour to get inserted into my database. I'm trying to improve the performance of this insert. I'm looking to insert all of the records within 5 to 10 minutes.
I am using For loop to populate each and every row to get insert into DB with a SQL transactions and I don't think that SqlBulkCopy will work out because all 200,000 records needs to be validated with the DB before insertion into DB.
Save-Function:
if (chkretailprice.Checked)
{
DataTable dt_grid = (DataTable)gcPromotion.DataSource;
dt_grid.AcceptChanges();
for (int tt = 0; tt < gvPromotion.RowCount; tt++)
{
gvPromotion.FocusedRowHandle = tt;
double dRGridMinus = Convert.ToDouble(gvPromotion.GetRowCellValue(tt, gvPromotion.Columns["PromotionalRetailPrice"]));
string sItem = Convert.ToString(gvPromotion.GetRowCellValue(tt, gvPromotion.Columns["ItemName"]).ToString());
string sPack = Convert.ToString(gvPromotion.GetRowCellValue(tt, gvPromotion.Columns["Package"]).ToString());
if (dRGridMinus < 0)
{
gvPromotion.FocusedRowHandle = tt;
MessageBoxInfo("Promotional RetailPrice contains Negative Values for this ItemName-'" + sItem + "' & Package-'" + sPack + "'");
gvPromotion.Focus();
return;
}
}
int iReCount = dt_grid.Select("PromotionalRetailPrice='0.00'").Length;
if (iReCount != 0)
{
MessageBoxInfo("Promotional RetailPrice Must not be 0");
gvPromotion.Focus();
return;
}
}
if (rgPromotion.Checked)
{
for (int p = 0; p < gvPromotion.RowCount; p++)
{
string[] sbranchArr = sBranchIDs.Split(',');
for (int pp = 0; pp < sbranchArr.Length; pp++)
{
objProEntity.PromotionMasterId = objProEntity.PromotionMasterId;
objProEntity.BranchId = Convert.ToInt32(sbranchArr[pp]);//gvPromotion.GetRowCellValue(p, gvPromotion.Columns["BranchID"]));
objProEntity.ItemId = Convert.ToInt64(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ItemID"]));
objProEntity.PackId = Convert.ToInt32(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PackTypeID"]));
objProEntity.PromotionValueType = Convert.ToString(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionValueType"]));
objProEntity.PromotionValue = Convert.ToString(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionValue"]));
if (chkretailprice.Checked && chkwholesaleprice.Checked)// when both retailprice & wholesaleprice checkbox is checked
{
objProEntity.ActualRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualRetailPrice"]));
objProEntity.PromoRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalRetailPrice"]));
objProEntity.ActualWholeSalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualWholeSalePrice"]));
objProEntity.PromoWholesalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalWholeSalePrice"]));
}
else if (chkretailprice.Checked)// when retailprice checkbox is checked
{
objProEntity.ActualRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualRetailPrice"]));
objProEntity.PromoRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalRetailPrice"]));
objProEntity.ActualWholeSalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualWholeSalePrice"]));
objProEntity.PromoWholesalePrice = Convert.ToDecimal(0);
}
else if (chkwholesaleprice.Checked)// when wholesaleprice checkbox is checked
{
objProEntity.ActualRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualRetailPrice"]));
objProEntity.PromoRetailPrice = Convert.ToDecimal(0);
objProEntity.ActualWholeSalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualWholeSalePrice"]));
objProEntity.PromoWholesalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalWholeSalePrice"]));
}
objProEntity.DiscountAllowed = Convert.ToBoolean(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["DiscountAllowed"]));
DataTable dt_Check = new DataTable();
dt_Check = SalesPromotionData.IsCheckItemExists(objProEntity, SQLTrans);
if (dt_Check.Rows.Count == 0)
{
if (!IsEdit)
{
DataTable dt_child = SalesPromotionData.InsertChildData(objProEntity, SQLTrans); // Insert Child Details when isEdit=false
}
else
{
if (gvPromotion.Columns.Contains(gvPromotion.Columns["PromotionChildId"]))
if ((DBNull.Value.Equals(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]))) || (gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]) == "") || Convert.ToString(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]).ToString()) == "0")
{
objProEntity.PromotionMasterId = masterid;
SalesPromotionData.InsertChildData(objProEntity, SQLTrans);// insert child details when isEdit=true
}
else
{
objProEntity.PromotionChildId = Convert.ToInt64(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]).ToString());
SalesPromotionData.UpdateChildDetails(objProEntity, SQLTrans); // update child details when isEdit=true
}
else
{
objProEntity.PromotionMasterId = masterid;
SalesPromotionData.InsertChildData(objProEntity, SQLTrans);// insert child details when isEdit=true
}
}
}
}
}
}
Normally, you'd stage your data into the database by bulk inserting it into [a] work table(s), with no referential integrity or anything -- just the raw data plus any [non-unique] indices you might need. Once you've got it staged, you can then:
Validate the data in the work table(s) against your database and
apply it to the "real" tables in question.
I want to remove a selected item in my combobox
I have here a code upon form load, I am filling list items on combobox from database.
private void LoadComboField()
{
//string test = "<ROOT><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"PNAME\" Output=\"1\" Filter=\"1\" FieldName=\"PATIENTNAME\" DataType=\"STRING\"/><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"MEMID\" Output=\"1\" Filter=\"1\" FieldName=\"MEMBERID\" DataType=\"STRING\"/></ROOT>";
ReadXMLData(XMLDOC, dsCombo);
// ReadXMLData(test, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Then I have this code on SelectedValueChanged
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
//this.dgvFilter.CurrentRow.IsNewRow
//if (GridRowLoc.IsNewRow) continue;
// MessageBox.Show(this.dgvFilter.RowCount.ToString());
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"]= this.cmbField.SelectedValue;
drow["Alias"]=string.Empty;
drow["DataType"]=string.Empty;
drow["Outputs"]=false;
drow["SortType"]=string.Empty;
drow["SortOrder"]=string.Empty;
drow["GroupBy"]=string.Empty;
drow["Filter"]=string.Empty;
drow["Or1"]=string.Empty;
drow["Or2"]=string.Empty;
drow["Or3"]=string.Empty;
drow["Or4"]=string.Empty;
drow["Or5"]=string.Empty;
drow["Or6"]=string.Empty;
drow["Or7"]=string.Empty;
drow["Or8"]=string.Empty;
drow["Or9"]=string.Empty;
drow["Or10"]=string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
// checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
I have this code in SelectedIndexChanged
try
{
DataTable dt1 = new DataTable();
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
//int count = dttable.Rows.Count - 1;
ComboBox comboBox = (ComboBox)sender;
// Save the selected employee's name, because we will remove
// the employee's name from the list.
string selectedEmployee = (string)sValue;
int count = 0;
int resultIndex = -1;
// Call the FindStringExact method to find the first
// occurrence in the list.
resultIndex = cmbField.FindStringExact(selectedEmployee);
// Remove the name as it is found, and increment the found count.
// Then call the FindStringExact method again, passing in the
// index of the current found item so the search starts there
// instead of at the beginning of the list.
while (resultIndex != -1)
{
cmbField.Items.RemoveAt(resultIndex);
count += 1;
resultIndex = cmbField.FindStringExact(selectedEmployee,
resultIndex);
}
// Update the text in Textbox1.
txtName.Text = txtName.Text + "\r\n" + selectedEmployee + ": "
+ count;
}
//}
catch (Exception ex)
{
}
But it throws an exception, say that "items collection cannot be modified when the datasource property is set." I don't know how to fix this exception error, I think that's my only problem when removing an item on the combobox.
Please do help me on this one. Thanks in advance!
Use a BindingSource for your DataSource and CurrentItemChanged to react of changed items in CBO:
this.source = new BindingSource();
this.source.DataSource = loDs.Tables[0];
this.cmbField.DataSource = this.source;
this.source.CurrentItemChanged += source_CurrentItemChanged;
Example for eventHandler:
private void source_CurrentItemChanged(object sender, EventArgs e)
{
System.Data.DataRowView view = this.source.Current as System.Data.DataRowView;
if (view != null)
{
System.Diagnostics.Debug.WriteLine(view[0].ToString());
}
}
You can remove an item from the source like this:
this.source.RemoveAt(this.source.Find("FieldName", "PATIENTNAME"));
Show Details: A Detailed Data Binding Tutorial
You can't modify the Items collection when it comes from / is bound to a DataSource. Instead you need to modify the DataSource itself.
To delete the SelectedItem from the DataSource you can try this:
DataRowView item = cmbField.SelectedItem as DataRowView;
if (item != null) item.Delete();
I have to wrote a DataGridView and filled it programmatically.
I want when the user searches the a word for example key and there is cell which contains it (for example its keyword) just highlight the searched word key in keyword not the all keyword or not the cell nor the row.
Here is the code for filling DataGridView:
private void Fill()
{
try
{
if (dataGridView1 != null)
{
dataGridView1.ColumnCount = 11;
dataGridView1.Columns[0].HeaderText = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].HeaderText = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].HeaderText = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].HeaderText = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].HeaderText = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].HeaderText = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].HeaderText = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].HeaderText = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].HeaderText = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].HeaderText = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].HeaderText = Resources.Form1_Fill_Address;
dataGridView1.Columns[0].Name = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].Name = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].Name = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].Name = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].Name = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].Name = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].Name = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].Name = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].Name = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].Name = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].Name = Resources.Form1_Fill_Address;
}
_conn.ConnectionString = _connectionString;
var cmd = new OleDbCommand("Select * from contacts ", _conn);
_conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader != null && reader.Read())
{
if (dataGridView1 != null)
{
dataGridView1.Rows.Add(1);
}
if (dataGridView1 != null)
{
var row = dataGridView1.Rows[i];
row.Cells[Resources.Form1_Fill_ID].Value = reader[0].ToString();
row.Cells[Resources.Form1_Fill_Family].Value = reader[1].ToString();
row.Cells[Resources.Form1_Fill_Cellphone].Value = reader[2].ToString();
row.Cells[Resources.Form1_Fill_Phone1].Value = reader[3].ToString();
row.Cells[Resources.Form1_Fill_Phone2].Value = reader[4].ToString();
row.Cells[Resources.Form1_Fill_Phone3].Value = reader[5].ToString();
row.Cells[Resources.Form1_Fill_Fax].Value = reader[6].ToString();
row.Cells[Resources.Form1_Fill_CompanyName].Value = reader[7].ToString();
row.Cells[Resources.Form1_Fill_Agency].Value = reader[8].ToString();
row.Cells[Resources.Form1_Fill_Brands].Value = reader[9].ToString();
row.Cells[Resources.Form1_Fill_Address].Value = reader[10].ToString();
}
i++;
}
}
catch (Exception ex)
{
return;
}
finally
{
_conn.Close();
}
}
and here is the search code
private void searchBtn_Click(object sender, EventArgs e)
{
// Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
if (row.Cells[0].Value.ToString().Contains(searchTxt.Text))
//row.Cells[0].Style.ForeColor = Color.Red;
{
var t = row.Cells[0].Value.ToString();
}
if (row.Cells[1].Value.ToString().Contains(searchTxt.Text))
row.Cells[1].Style.ForeColor = Color.Red;
if (row.Cells[2].Value.ToString().Contains(searchTxt.Text))
row.Cells[2].Style.ForeColor = Color.Red;
if (row.Cells[3].Value.ToString().Contains(searchTxt.Text))
row.Cells[3].Style.ForeColor = Color.Red;
if (row.Cells[4].Value.ToString().Contains(searchTxt.Text))
row.Cells[4].Style.ForeColor = Color.Red;
if (row.Cells[5].Value.ToString().Contains(searchTxt.Text))
row.Cells[5].Style.ForeColor = Color.Red;
if (row.Cells[6].Value.ToString().Contains(searchTxt.Text))
row.Cells[6].Style.ForeColor = Color.Red;
if (row.Cells[7].Value.ToString().Contains(searchTxt.Text))
row.Cells[7].Style.ForeColor = Color.Red;
if (row.Cells[8].Value.ToString().Contains(searchTxt.Text))
row.Cells[8].Style.ForeColor = Color.Red;
if (row.Cells[9].Value.ToString().Contains(searchTxt.Text))
row.Cells[9].Style.ForeColor = Color.Red;
if (row.Cells[10].Value.ToString().Contains(searchTxt.Text))
row.Cells[10].Style.ForeColor = Color.Red;
}
catch (Exception)
{
return;
}
}
}
If this search is only depend upon client side loaded data then why don't you suggest to customer use browser search functionality.
If still you have to provide this functionality to customer then why you are going at server side code to do this task.... you can handle this in javascript.
Following are the example Link which explains about how to access datagridview in javascript.
http://www.netomatix.com/development/gridviewclientsideaccess.aspx
http://www.thescarms.com/dotnet/webdatagrid.aspx
It's not possible with standard .NET controls.
You can try Telerik winform suite or similar, which controls allowing to use HTML formatting to highlight only a part of the text.
Do you really need DataGridView? If you use it to display data only, you can also try using WebBrowser control and draw an html table there.
You should also refactor your search code:
for(int i=0; i<11; i++)
{
if (row.Cells[i].Value.ToString().Contains(searchTxt.Text))
row.Cells[i].Style.ForeColor = Color.Red;
}