My gridview missing previous data when post back. Here is the scenario, when I detect insufficient stock from gvFinalised gridview, I get the category, then I get the product with highest stock and display in gvSuggested gridview.
But let's say in my gvFinalised, there are three product with three different categories is insufficient, let's say they are Noodles, Canned Food and Beverages. It was supposed to display three different products with highest stock each from different categories in gvSuggested.
However, my problem now is, it just display the last items. For example, in this scenario, Beverages. The data before Beverages just get wiped out.
Here is the code on how I detect insufficient stock:
protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
tempList = new Dictionary<string, string>();
distSPUItemList = new Dictionary<string, int>();
bool valid = true;
string quantityStr = "", prodID = "";
int packagesNeeded = 0, totalUnit = 0, quantity = 0;
//Get the total packages needed for this distribution
packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
foreach (GridViewRow gr in gvFinalised.Rows)
{
//Clear label error message
Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
lblCheckAmount.Text = "";
//Get the product variant ID which set as DataKeyNames and product quantity from selected row index
prodID = gvFinalised.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
//Check if the input is numeric
quantityStr = tbQuantity.Text;
if (!int.TryParse(quantityStr, out quantity))
{
lblCheckAmount.Text = "Non-numeric input!";
TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
}
else
{
//Add both objects into Dictionary
tempList.Add(prodID, quantityStr);
}
}
}
//Portion to check the storage level for each products stored in tempList
//Loop thru tempList. key as prod variant ID, tempList.Keys as quantity
foreach (string key in tempList.Keys)
{
//Get total unit of each products
totalUnit = prodPackBLL.getTotalProductUnit(key);
valid = true;
//Check if unitQuantity exceed storage level
if (((Convert.ToInt32(tempList[key])) * packagesNeeded) > totalUnit)
{
//Get the label control in gridview
foreach (GridViewRow gr in gvFinalised.Rows)
{
if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
{
//Change the color of textBox and display the insufficient message
valid = false;
//Automatically uncheck the checkBox if invalid
TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
lblCheckAmount.Text = "Insufficient stock!";
//Here is the place where I collect the data and display in gvSuggested
getSuggested(key);
}
}
}
else
{
if (totalUnit - ((Convert.ToInt32(tempList[key])) * packagesNeeded) == 0)
{
foreach (GridViewRow gr in gvFinalised.Rows)
{
if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
{
valid = true;
Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
lblCheckAmount.Attributes["style"] = "color:#ffb848";
lblCheckAmount.Text = "Stock becomes 0!";
}
}
}
}
//Portion to check for valid products to be inserted into distSPUItemList
if (valid)
{
//Set the textBox color
foreach (GridViewRow gr in gvFinalised.Rows)
{
if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
{
TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
}
}
//Validated items store into another list to perform Sql statement when button on click
distSPUItemList.Add(key, (Convert.ToInt32(tempList[key]) * packagesNeeded));
}
}
}
And here is the getSuggested() method to populate my gvSuggeted:
protected void getSuggested(string prodVariantID)
{
string categoryName = prodPackBLL.getCategoryByProdVariantID(prodVariantID);
//Get the list of substitute product with highest storage level sorted in descending order
List<ProductPacking> prodSubstitute = new List<ProductPacking>();
List<string> lstCategory = new List<string>();
List<string> prodIDList = new List<string>();
List<DistributionStandardPackingUnitItems> distSPUItem = new List<DistributionStandardPackingUnitItems>();
distSPUItem = this.SuggestedItems;
//Find list of substitute with highest stock level and replace the product
prodSubstitute = prodPackBLL.getProductIDWithHighestStock(categoryName);
for (int count = 0; count < prodSubstitute.Count; count++)
{
//To prevent duplication of same product and select those catories which are in current category and counting them and taking them if there are less than 1 occurrences
if (!prodIDList.Contains(prodSubstitute[count].id) && !(lstCategory.Where(x => x.Equals(categoryName)).Select(x => x).Count() >= 2))
{
prodIDList.Add(prodSubstitute[count].id);
lstCategory.Add(categoryName);
}
}
for (int j = 0; j < prodIDList.Count; j++)
{
//Get the detail of the product added into prodList and add it into distSPUItem List
distSPUItem.Add(packBLL.getSPUItemDetailByID(prodIDList[j]));
}
gvSuggested.DataSource = distSPUItem;
gvSuggested.DataBind();
this.SuggestedItems = distSPUItem;
}
private List<DistributionStandardPackingUnitItems> SuggestedItems
{
get
{
if (ViewState["SuggestedItems"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["SuggestedItems"];
}
}
set
{
ViewState["SuggestedItems"] = value;
}
}
I used a viewState to store the data when postback. However, it does not work. This line in gvSuggested:
this.SuggestedItems = distSPUItem;
causing my textbox in gridView not auto post back. If I removed it, the error above appear again. Any guides? Thanks in advance.
Please enable tbQuantity text box EnableAutoPostBack = True
Related
I want to use the virtual mode of a DataGridView since I have more than 150k rows (always 2 columns). The data in the DataGridView is extracted from a file and is read-only(users can't add or remove rows). However, some of my rows needs to have a greater height than the others since the data displayed in it is on multiple lines.
I am currently filling my DataGridView like this:
private struct ContactEntry
{
public string Name { get; set; }
public string Addr { get; set; }
};
private void UpdateDataGridView(List<Contact> listContact)
{
List<ContactEntry> newList = new List<ContactEntry>();
for (int index = 0; index < listContact.Count; index++)
{
Contact ct = listContact[index];
string addresses = string.Empty;
if (Contact.Addrs != null)
{
// Construct list of addresses
foreach (string addr in Contact.Addrs)
{
addresses = String.Format("{0}{1}{2}", addresses, Environment.NewLine, addr);
}
// Removes first environment new line
addresses = addresses.Remove(0, 2);
var entry = new ContactEntry();
entry.Name = Contact.Name;
entry.Addr = addresses;
newList.Add(entry);
}
}
_dgvContacts = newList;
_dgvContacts.CellValueNeeded += _dgvContacts_CellValueNeeded;
// Set the row count
_dgvContacts.RowCount = newList.Count;
_dgvContacts.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
_dgvContacts.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
if (_dgvContacts.CurrentCell != null)
{
_dgvContacts.CurrentCell.Selected = false;
}
}
private void _dgvContacts_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
switch (_dgvContacts.Columns[e.ColumnIndex].Name)
{
case "Name":
e.Value = _dgvContacts[e.RowIndex].Name;
break;
case "Addresses":
e.Value = _dgvContacts[e.RowIndex].Addr;
break;
}
}
With this, the UI loads quickly because of the virtual mode, but when the form loads, only the height of the first visible rows are adjusted. When I scroll down, the data in the rows are changed for new values from the list, but the height are not changing. However, when I resize the form, the rows height are updated like it should.
I have a datagridview named PTable which shows a table from database. I also have a button that functions to copy the data from selected rows to the textboxes I have.
This code that I have right now copies two selected rows from the datagridview but when I only select one row or when I select more than 2 rows, it says that "Index was out of range"
What should happen is that it should copy any number of rows and not only 2 rows
private void button11_Click(object sender, EventArgs e)
{
productid.Text = PTable.SelectedRows[0].Cells[0].Value + string.Empty;
productname.Text = PTable.SelectedRows[0].Cells[1].Value + string.Empty;
unitprice.Text = PTable.SelectedRows[0].Cells[4].Value + string.Empty;
productid2.Text = PTable.SelectedRows[1].Cells[0].Value + string.Empty;
productname2.Text = PTable.SelectedRows[1].Cells[1].Value + string.Empty;
unitprice2.Text = PTable.SelectedRows[1].Cells[4].Value + string.Empty;
}
If a user have not selected two rows, your index 1 (PTable.SelectedRows[1]) is not valid, because the item is not there.
Before you can run this code, you have to check, if the user selected two rows:
if (PTable.SelectedRows.Count == 2)
{
//Your code ...
}
else
{
//Not two rows selected
}
First, make sure SelectionMode of DataGridView to FullRowSelect(Hope you have done it already)
Second, Use foreach or any looping logic to go through each selected rows.
Third, It's always better to write modular code. Write a validation method which returns TRUE or FALSE based on selection of the grid rows.
Now based on returned value you need to continue writing your business logic.
Fourth, Make sure to use NULL checks
So let's start by re-factoring the code.
private void button11_Click(object sender, EventArgs e)
{
If(IsRowOrCellSelected())
{
//loop through selected rows and pick your values.
}
}
I am just writing sample, make sure PTable is accessible.
private boolean IsRowOrCellSelected()
{
if (PTable.SelectedRows.Count > 0)
{
DataGridViewRow currentRow = PTable.SelectedRows[0];
if (currentRow.Cells.Count > 0)
{
bool rowIsEmpty = true;
foreach(DataGridViewCell cell in currentRow.Cells)
{
if(cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
}
if(rowIsEmpty)
return false;
else
return true;
}
Code can be still improved.
To work with varying number of selected rows I suggest the following.
My approach is:
There may be more than 5 rows, that You have to display. First create 3 panels for the TextBoxes. I have named the one for the productids as here. Generate the textboxes from code, this way it's easier to maintain more than 5 selected rows:
// This code goes to the constructor of the class. Not in the button click
List<TextBox> productids = new List<TextBox>();
List<TextBox> productnames = new List<TextBox>();
List<TextBox> unitprices = new List<TextBox>();
for (int i = 0; i < 5; i++)
{
productids.Add(new TextBox { Top = i * 32 });
productnames.Add(new TextBox { Top = i * 32 });
unitprices.Add(new TextBox { Top = i * 32 });
here.Controls.Add(productids[i]);
here2.Controls.Add(productnames[i]);
here3.Controls.Add(unitprices[i]);
}
Than You can in the button click set the value for each selected row:
// This code goes to the button click
// first empty the Textboxes:
foreach (TextBox productid in productids)
{
productid.Text = string.Empty;
}
foreach (TextBox productname in productnames)
{
productname.Text = string.Empty;
}
foreach (TextBox unitprice in unitprices)
{
unitprice.Text = string.Empty;
}
for (int i = 0; i < PTable.SelectedRows.Count; i++)
{
productids[i].Text = PTable.SelectedRows[i].Cells[0].Value.ToString();
productnames[i].Text = PTable.SelectedRows[i].Cells[1].Value.ToString();
// or better... Name the columns
// unitprices[i].Text = PTable.SelectedRows[i].Cells["unitPrices"].Value.ToString();
unitprices[i].Text = PTable.SelectedRows[i].Cells[4].Value.ToString();
}
I have a page with a listing of products in a table (which is built with divs but I digress), and one column is called "Add to Shopping List" and contains a checkbox. If that checkbox is checked, then the product for that row should be placed into the user's order. On submission, the user is taken to an order review page with all the items they had selected.
The problem right now is that, even though I set the quantity of a product to "1" when the checkbox is selected, every time the form is submitted, the number of items selected for ordering is always 0.
The function that is meant to see if any items have been selected for ordering upon submission is called checkQtys:
protected bool checkQtys(ref int ItemCnt, ref ArrayList LinesToOrder)
{
Repeater locationRepeater = (Repeater)FindControl("locationRepeater");
bool validQtys = true;
string productID = "";
int qty;
qtyErrorMsg.Text = "";
qtyErrorMsgTop.Text = "";
foreach (RepeaterItem repItem in locationRepeater.Items)
{
if (repItem != null)
{
Repeater areaRepeater = (Repeater)repItem.FindControl("areaRepeater");
if (areaRepeater != null)
{
foreach (RepeaterItem skuItm in areaRepeater.Items)
{
if (skuItm != null)
{
Label SkuID = (Label)skuItm.FindControl("SkuID");
Label qtyID = (Label)skuItm.FindControl("qtyID");
PlaceHolder inner = (PlaceHolder)skuItm.FindControl("ProductTable");
if (inner != null)
{
foreach (Control ct in inner.Controls)
{
if (ct is CheckBox)
{
CheckBox lineQty = (CheckBox)ct;
Label prodID = (Label)inner.FindControl("productID");
if (lineQty.Checked)
{
productID = prodID.Text;
qty = 1;
LinesToOrder.Add(new LineItem(productID, qty));
ItemCnt++;
validQtys = true;
}
}
}
}
}
}
}
}
}
return validQtys;
}
*Note: This original was meant to check a textbox value--the "Add To Shopping List" column was originally set to take user input for specific quantities but that has been changed to the checkbox.
This is the submit function:
protected void orderSubmit(object sender, EventArgs e)
{
int ItemCnt = 0;
bool validQtys = true;
ArrayList LinesToOrder = new ArrayList();
Label lb = FindControl("order") as Label;
if (checkQtys(ref ItemCnt, ref LinesToOrder))
{
string value = checkQtys(ref ItemCnt, ref LinesToOrder).ToString();
Response.Write("value: " + value + "<br />");
if (ItemCnt == 0)
{//make sure at least one item with proper qty amount is entered before submitting the order
validQtys = false;
noItemMsg.Visible = true;
noItemMsg.Text = "<br /><br />You must order at least one item<br />";
noItemMsgTop.Visible = true;
noItemMsgTop.Text = "You must order at least one item<br />";
}
if (validQtys)
{//save the information to a session variable and send users to order review page
try
{
foreach (LineItem WorkLine in LinesToOrder)
{
lb.Text += WorkLine.SKUID + ", " + WorkLine.Qty + ";";
}
Session["orderComplete"] = lb.Text;
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
Response.Redirect("/united-states/market/office-buildings/obproductmap/OrderReview");
}
}
}
What happens in the above function is that ItemCnt is always 0, and thus the user never can go to the order review page even if they have checked at least one of the checkboxes in the product listing table. I have no clue why this is happening--with the ref int value for ItemCnt being set in checkQtys, it should not be coming in as 0 in orderSubmit unless it is actually 0.
What am I missing?
So basically I am doing a manage packaging item system. The scenario is, when I select from gvSPU, gvFinalised should display the item in database. After that, when I add new item into the gvFinalised, it supposed to keep stacking up the items instead of wiping out the previous record and display the added latest one. Here is the code:
private List<DistributionStandardPackingUnitItems> tempDistSPUI
{
get
{
if (ViewState["tempDistSPUI"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["tempDistSPUI"];
}
}
set
{
ViewState["tempDistSPUI"] = value;
}
}
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
List<DistributionStandardPackingUnitItems> templist = new List<DistributionStandardPackingUnitItems>();
templist = tempDistSPUI;
templist = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = templist;
gvFinalised.DataBind();
this.tempDistSPUI = templist;
}
When gvSPU row is selected, it should store all the records into templist and display in gvFinalised.
List<string> prodVariantIDList = new List<string>();
private List<string> SelectedVariantDetailIDs
{
get
{
if (ViewState["SelectedVariantDetailIDs"] == null)
{
return new List<string>();
}
else
{
return (List<string>)ViewState["SelectedVariantDetailIDs"];
}
}
set
{
ViewState["SelectedVariantDetailIDs"] = value;
}
}
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<ProductPacking> prodVariantDetail = new List<ProductPacking>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(prodPackBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
When add button is on click, it should append with the record in gridview instead of wiping them off and insert the checked one.
I am using the viewState to store the record between postbacks. However, when I try to add new item into gvFinalised, the previous record which in the templist will disappear and the gvFinalised will be populated with the result from prodVariantDetail list.
Any guide? Thanks in advance.
EDIT
List<DistributionStandardPackingUnitItems> itemList = new List<DistributionStandardPackingUnitItems>();
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
itemList = tempDistSPUI;
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = itemList;
gvFinalised.DataBind();
this.tempDistSPUI = itemList;
}
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
for (int j = 0; j < itemList.Count; j++)
{
prodVariantDetail.Add(itemList[j]);
}
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
}
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
You have to add the elements of tempDistSPUI into prodVariantDetail before binding prodVariantDetail to gvFinalised.
Here's what I would do using List.AddRange Method:
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
// get the content of tempDistSPUI from ViewState
itemList = this.tempDistSPUI;
// add all elements of itemList to prodVariantDetail
prodVariantDetail.AddRange(itemList);
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
The code below lets me show emails received in a listview on when the selected index is changed displays the body of the selected email in a RTB. The problem is i changed the code to work with a data grid view and now the Tag part wont work
void SomeFunc() // This line added by Jon
{
int i;
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
ListViewItem itmp = new ListViewItem(email.From);
ListViewItem.ListViewSubItem itms1 =
new ListViewItem.ListViewSubItem(itmp, email.Subject);
ListViewItem.ListViewSubItem itms2 =
new ListViewItem.ListViewSubItem(itmp, email.FromName);
itmp.SubItems.Add(itms1);
itmp.SubItems.Add(itms2);
listView1.Items.Add(itmp).Tag = i;
richTextBox1.Text = email.Body;
}
// Save the email to an XML file
bundle.SaveXml("email.xml");
}
private void listView1_SelectionChanged(object sender, EventArgs e)
{
if (listView1.SelectedCells.Count > 0)
{
// bundle is now accessible in your event handler:
richTextBox1.Text = bundle.GetEmail((int)listView1.SelectedCells[0].Tag).Body;
}
}
Code for data grid view
int i;
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
string[] row = new string[] { email.From, email.Subject, email.FromName };
object[] rows = new object[] { row };
foreach (string[] rowArray in rows)
{
dataGridView1.Rows.Add(rowArray);
}
} // This line added by Jon
i have created earlier the code for datagrid view but you already done it so i haven't posted in your last question but i think , you should give a try to the below code.
// i am creating a new object here but , you can have a single object on the form
DataGridView dgv = new DataGridView();
private DataTable EmailSource { get; set; }
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.SelectionChanged+=new EventHandler(dgv_SelectionChanged);
Chilkat.MessageSet msgSet = imap.Search("ALL", true);
if (msgSet != null)
{
bundle = imap.FetchBundle(msgSet);
CreateDataTable();
if (bundle != null && dt!=null)
{
Chilkat.Email email;
int i;
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
if(email!=null)
{
DataRow drow = EmailSource.NewRow();
drow["Id"] = i.ToString();
drow["From"] = email.FromName;
drow["Subject"] = email.Subject;
drow["DateRecived"] = email.DateRecived;
// i am adding email body also
drow["Body"] =email.Body;
EmailSource.Rows.Add(drow);
}
}
// Save the email to an XML file
bundle.SaveXml("email.xml");
dgv.DataSource= EmailSource;
// Hiding Body from the grid
dgv.Columns["Body"].Visible =false;
}
}
// this event handler will show the last selected email.
void dgv_SelectionChanged(object sender, EventArgs e)
{
DataGridViewSelectedRowCollection rows = dgv.SelectedRows;
if (rows != null)
{
// get the last selected row
DataRow drow = rows[rows.Count - 1].DataBoundItem as DataRow;
if (drow != null)
{
richTextBox1.Text = drow["Body"];
}
}
}
private void CreateDataTable()
{
EmailSource = new DataTable();
EmailSource.Columns.Add("Id");
EmailSource.Columns.Add("From");
EmailSource.Columns.Add("Subject");
EmailSource.Columns.Add("DateRecived");
EmailSource.Columns.Add("Body");
}
You are adding rows using listView1.Rows.Add(rowArray) in both the code listings. Is that a typo or you named the GridView like that.
Basically, you are storing the index of the email in the "Tag" property.
listView1.Items.Add(itmp).Tag = i;
You need to make sure that you do the same while adding items to the GridView too.
The DataGridView does not have an "Items" collection. To make it work, you need to bind the DataGridView to a collection of objects. Something like this should get you started:
List<Email> emails = new List<Email>();
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
emails.Add(email);
}
dataGridView.ItemsSource = emails;
You should not need to store the row index for each item in a "Tag" object - you can can get the selected index like this:
int selectedIndex = dataGridView.SelectedCells[0].RowIndex;