I have this code retrieving data from a database but my problem is that it only shows the last item on my ListViewItem. Here is the code:
private void patientLvw_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
cmd = new OleDbCommand("SELECT * FROM PATIENTS ORDER BY PATIENTS.PatientNo;", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
String patientNo = ""; ;
String lastName = "";
String firstName = "";
String middleInitial = "";
String age = "";
String address = "";
String type = "";
String status = "";
if (!reader.IsDBNull(0))
{
patientNo = reader.GetInt32(0).ToString();
}
if (!reader.IsDBNull(1))
{
lastName = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
firstName = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
middleInitial = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
age = reader.GetInt32(4).ToString();
}
if (!reader.IsDBNull(5))
{
address = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
type = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
status = reader.GetBoolean(7).ToString();
}
ListViewItem lvi = new ListViewItem(patientNo);
e.Item.SubItems.Add(lastName);
e.Item.SubItems.Add(firstName);
e.Item.SubItems.Add(middleInitial + ".");
e.Item.SubItems.Add(age);
e.Item.SubItems.Add(address + ".");
e.Item.SubItems.Add(type);
e.Item.SubItems.Add(status);
e.Item = lvi;
}
}
RetreiveVirtualItem is called for each item, and you are looping though every patient every time it is called. You overwrite e.Item each time, so each item ends up with the last set of values.
You need to check e.ItemIndex and only retrieve the data for that particular row.
Or maybe you don't actually want to use virtual mode, and you should just do the query once on startup and manually add them all to the list.
Answer from before question was edited:
Also, why are you creating two ListViewItems? I think your code should be this:
e.Item = new ListViewItem(patientNo);
if (status.Equals("Yes"))
{
e.Item.ForeColor = Color.Red;
}
e.Item.SubItems.Add(lastName);
e.Item.SubItems.Add(firstName);
e.Item.SubItems.Add(middleInitial + ".");
e.Item.SubItems.Add(age));
e.Item.SubItems.Add(address + ".");
e.Item.SubItems.Add(type);
e.Item.SubItems.Add(status);
Related
I have a simple CSV file I need to parse that has variable column lengths. CSV File for reference.
I'm attempting to write some conditions to parse each line and store into a discreet string based off what value the first column contains in each line.
The first issue that I'm running into is that my loop seems to start reading at row 2. Is this because TextFieldParser assumes a header?
The second issue is that my if statements don't seem to be evaluating correctly. If I shift the order of the rows within the file, my first if in the order is supposed to parse the "Lighting" rows (regardless of which rows in the file contain "Lighting").
Just as a note, I am working in a .net 3.5 environment
Here's what I've got so far:
namespace CSV_Handler_Console
{
public class Program
{
public static void Main(string[] args)
{
//Console.WriteLine("Press Enter");
string filePath = "C:\\Users\\chris\\Desktop\\ConfigFile.csv";
string subLight = "Lighting";
string subPin = "PIN";
string subProc = "Processor";
string subFab = "Fabuloso";
string subQuirky = "Quirky";
//string[] fields = csvParser.ReadFields();
string category = string.Empty;
string index = string.Empty;
string load1 = string.Empty;
string load2 = string.Empty;
string load3 = string.Empty;
string load4 = string.Empty;
string value = string.Empty;
string light1 = string.Empty;
string light2 = string.Empty;
string light3 = string.Empty;
string pin = string.Empty;
string processor1 = string.Empty;
string processor2 = string.Empty;
string processor3 = string.Empty;
string processor4 = string.Empty;
string processor5 = string.Empty;
string processor6 = string.Empty;
string processor7 = string.Empty;
string processor8 = string.Empty;
string display1 = string.Empty;
string display2 = string.Empty;
string display3 = string.Empty;
string display4 = string.Empty;
string display5 = string.Empty;
string display6 = string.Empty;
string display7 = string.Empty;
string display8 = string.Empty;
var path = String.Format("{0}", filePath);
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.SetDelimiters(new string[] { "," });
//csvParser.HasFieldsEnclosedInQuotes = false;
string row = csvParser.ReadLine();
while (!csvParser.EndOfData)
{
if (row.Contains(subLight))
{
string[] fields = csvParser.ReadFields();
category = fields[0];
index = fields[1];
load1 = fields[2];
load2 = fields[3];
load3 = fields[4];
load4 = fields[5];
if(index.Contains("1"))
{
light1 = row;
}
else if (index.Contains("2"))
{
light2 = row;
}
else if (index.Contains("3"))
{
light3 = row;
}
string rowData = string.Format("{0},{1},{2},{3},{4},{5}", category, index, load1, load2, load3, load4);
Console.WriteLine(rowData);
//Console.ReadLine();
}
else if (row.Contains(subPin))
{
string[] fields = csvParser.ReadFields();
category = fields[0];
index = fields[1];
value = fields[2];
string rowData = string.Format("{0},{1},{2}", category, index, value);
Console.WriteLine(rowData);
}
else if (row.Contains(subProc))
{
string[] fields = csvParser.ReadFields();
category = fields[0];
index = fields[1];
value = fields[2];
if (index.Contains("A"))
{
processor1 = row;
}
else if (index.Contains("B"))
{
processor2 = row;
}
else if (index.Contains("C"))
{
processor3 = row;
}
else if (index.Contains("D"))
{
processor4 = row;
}
else if (index.Contains("E"))
{
processor5 = row;
}
else if (index.Contains("F"))
{
processor6 = row;
}
else if (index.Contains("G"))
{
processor7 = row;
}
else if (index.Contains("H"))
{
processor8 = row;
}
string rowData = string.Format("{0},{1},{2}", category, index, value);
Console.WriteLine(rowData);
}
else if (row.Contains(subQuirky) || row.Contains(subFab))
{
string[] fields = csvParser.ReadFields();
category = fields[0];
index = fields[1];
value = fields[2];
if (index.Contains("A"))
{
display1 = row;
}
else if (index.Contains("B"))
{
display2 = row;
}
else if (index.Contains("C"))
{
display3 = row;
}
else if (index.Contains("D"))
{
display4 = row;
}
else if (index.Contains("E"))
{
display5 = row;
}
else if (index.Contains("F"))
{
display6 = row;
}
else if (index.Contains("G"))
{
display7 = row;
}
else if (index.Contains("H"))
{
display8 = row;
}
string rowData = string.Format("{0},{1},{2}", category, index, value);
Console.WriteLine(rowData);
}
else
{
Console.WriteLine("No Match Found");
}
}
Console.ReadLine();
}
}
}
Any guidance would be appreciated.
It's your implementation. You first grab the first row with ReadLine, which advances the cursor to the next line. Then if the row contains your search property, you do a ReadFields, which is the 2nd line of the document.
If your data is always guaranteed to have the category, you could just use ReadFields and compare against the first element. You could look at PeekChars if you want to look at the content of the current row without advancing the cursor.
TextFieldParser.ReadLine: Returns the current line as a string and
advances the cursor to the next line.
TextFieldParser.ReadFields: Reads all fields on the current line,
returns them as an array of strings, and advances the cursor to the
next line containing data.
TextFieldParser.PeekChars: Reads the specified number of characters without advancing the cursor.
here i want to append the product id of new product in the cookie name cart so can anyone help me with it
protected void lnkAddToCart_Click(object sender, EventArgs e)
{
HttpCookie CartCookie=Request.Cookies["cart"];
if (CartCookie != null)
{
string str = CartCookie.ToString();
str= str + ";"+ _ProductID.ToString();
Response.Cookies["cart"].Value = str;
}
else
{
CartCookie = new HttpCookie("cart");
CartCookie["Cart"] = _ProductID.ToString();
CartCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(CartCookie);
}
}
To Set Cookie
public void AddToCartCookie(List<string> listCookie)
{
string objCartListString = string.Join(",", listCookie);
if (Request.Cookies["CartCookie"] == null)
Response.Cookies["CartCookie"].Value = objCartListString;
else
Response.Cookies["CartCookie"].Value = Request.Cookies["CartCookie"].Value + "|" + objCartListString;
Response.Cookies["CartCookie"].Expires = DateTime.Now.AddYears(30);
}
Here listCookie is list of string like
string productName, quantity, price etc;
Then retrieve it by splitting like
if (Request.Cookies["CartCookie"] != null)
{
string objCartListString = Request.Cookies["CartCookie"].Value.ToString();
string[] objCartListStringSplit = objCartListString.Split('|');
foreach(string s in objCartListStringSplit)
{
string[] ss = s.Split(',');
productName = ss[0];
quantity = Convert.ToDouble(ss[1]);
price = Convert.ToDecimal(ss[3]);
.........
}
}
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
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.
}
}
}
I have two dropdownlist controls on an add/edit form page, one for countries (called CountryCode) and one for regions/states (called ProvinceCode). The code has been set up so that, when users select "United States" from the country dropdownlist, then the region dropdownlist is populated with all valid US states. If the user selects "Canada" from the country dropdownlist, then the region dropdownlist is populated with valid provinces. This functionality works fine, but when "Canada" is selected, for some reason, the region dropdownlist's value is never saved to the database. I am not sure why this is, especially since I can save US states just fine.
This is the code that is meant to populate the country and region dropdownlists:
protected void Page_Init(object sender, EventArgs e)
{
CountryCode.DataSource = CountryDataSource.LoadAll("Name");
CountryCode.DataBind();
InitCountryAndProvince();
}
private void InitCountryAndProvince()
{
//MAKE SURE THE CORRECT ADDRESS IS SELECTED
Address address = this.Address;
bool foundCountry = false;
if (!string.IsNullOrEmpty(address.CountryCode))
{
ListItem selectedCountry = CountryCode.Items.FindByValue(address.CountryCode);
if (selectedCountry != null)
{
CountryCode.SelectedIndex = CountryCode.Items.IndexOf(selectedCountry);
foundCountry = true;
}
}
if (!foundCountry)
{
Warehouse defaultWarehouse = AbleContext.Current.Store.DefaultWarehouse;
ListItem selectedCountry = CountryCode.Items.FindByValue(defaultWarehouse.CountryCode);
if (selectedCountry != null) CountryCode.SelectedIndex = CountryCode.Items.IndexOf(selectedCountry);
}
//MAKE SURE THE PROVINCE LIST IS CORRECT FOR THE COUNTRY
UpdateCountry();
//NOW LOOK FOR THE PROVINCE TO SET
ListItem selectedProvince = ProvinceCode.Items.FindByValue(address.Province);
if (selectedProvince != null) ProvinceCode.SelectedIndex = ProvinceCode.Items.IndexOf(selectedProvince);
}
private void UpdateCountry()
{
//SEE WHETHER POSTAL CODE IS REQUIRED
string[] countries = AbleContext.Current.Store.Settings.PostalCodeCountries.Split(",".ToCharArray());
//PostalCodeRequired.Enabled = (Array.IndexOf(countries, Country.SelectedValue) > -1);
//SEE WHETHER PROVINCE LIST IS DEFINED
IList<Province> provinces = ProvinceDataSource.LoadForCountry(CountryCode.SelectedValue);
if (provinces.Count > 0)
{
IEnumerable<Province> sortedProvinces = provinces.OrderBy(f => f.Name);
provinces = sortedProvinces.ToList();
ProvinceCode.Visible = false;
ProvinceCode.Visible = true;
ProvinceCode.Items.Clear();
ProvinceCode.Items.Add(string.Empty);
foreach (Province province in provinces)
{
string provinceValue = (!string.IsNullOrEmpty(province.ProvinceCode) ? province.ProvinceCode : province.Name);
ProvinceCode.Items.Add(new ListItem(province.Name, provinceValue));
}
ListItem selectedProvince = FindSelectedProvince();
if (selectedProvince != null) selectedProvince.Selected = true;
ProvinceCode.Enabled = true;
ProvinceCode.Text = string.Empty;
}
else
{
ProvinceCode.Visible = true;
ProvinceCode.Visible = false;
ProvinceCode.Items.Clear();
//Province2Required.Enabled = false;
}
}
private ListItem FindSelectedProvince()
{
string defaultValue = ProvinceCode.Text;
if (string.IsNullOrEmpty(defaultValue)) defaultValue = Request.Form[ProvinceCode.UniqueID];
if (string.IsNullOrEmpty(defaultValue)) return null;
defaultValue = defaultValue.ToUpperInvariant();
foreach (ListItem item in ProvinceCode.Items)
{
string itemText = item.Text.ToUpperInvariant();
string itemValue = item.Value.ToUpperInvariant();
if (itemText == defaultValue || itemValue == defaultValue) return item;
}
return null;
}
protected void Country_Changed(object sender, EventArgs e)
{
//UPDATE THE FORM FOR THE NEW COUNTRY
UpdateCountry();
}
This is the section of the save method that contains the country and region dropdownlist controls:
private void SaveCustomerInfo(int CustID)
{
int currentUserID = AbleContext.Current.UserId;
string editQuery = "UPDATE Customers SET BillToRegion = #BillToRegion, BillToCountry = #BillToCountry WHERE CustomerID = #CustomerID";
string addQuery = "INSERT INTO Customers (BillToRegion, BillToCountry) VALUES(#BillToRegion, #BillToCountry)";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Parameters.Add(new SqlParameter("#BillToRegion", ProvinceCode.SelectedValue));
cmd.Parameters.Add(new SqlParameter("#BillToCountry", CountryCode.SelectedValue));
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception exception)
{
Logger.Warn("Admin\\People\\Customers\\EditCustomer.aspx - SaveCustomerInfo", exception);
}
And this is the code that is called when the page loads to populate fields with values from the database (if the user is editing an existing entry):
protected void Page_Load(object sender, EventArgs e)
{
_CustomerID = AlwaysConvert.ToInt(Request.QueryString["CustomerID"]);
int.TryParse(Request.QueryString["CustomerID"], out _CustomerID);
if (_CustomerID == 0)
{
AddBtn.Visible = true;
EditBtn.Visible = false;
}
else
{
custIDHidden.Value = _CustomerID.ToString();
AddBtn.Visible = false;
EditBtn.Visible = true;
}
if (!Page.IsPostBack)
{
if (_CustomerID != 0)
{
string selectQuery = "BillToRegion, BillToCountry FROM Customers WHERE CustomerID = #CustomerID";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand(selectQuery, cn);
cmd.Parameters.Add(new SqlParameter("#CustomerID", custIDHidden.Value));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ProvinceCode.SelectedValue = reader["BillToRegion"].ToString();
CountryCode.SelectedValue = reader["BillToCountry"].ToString();
}
}
cn.Close();
}
}
catch (Exception x)
{
Logger.Warn("Admin\\People\\Customers\\EditCustomer.aspx - Page_Load", x);
}
}
}
}