Getting textBox value of checked row in grid view - c#

I am having some problem for getting the text from textbox in a row which the checkbox was marked check in gridview. When button on click, it supposed to get the checked row index for prodID and the quantity which is the text from textbox:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
string quantity = "" , prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity;
}
}
Let's say I got prodID 1 with 50 units, prodID 2 with 77 units, prodID 3 with 90 units. When I loop thru the tempList, this is the result which I supposed to get:
1 50units, 2 77units, 390units
However, the codes does not get the quantity from the textbox for each product independently. Here is the result which I get:
1 90units, 2 90units, 3 90units
It just simply get the quantity of last product in the list. I wonder is there any way to fix this? Thanks in advance.
Edited Portion:
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(tempList[key]);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(quantity) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}

You can use Dictionary to pair each prodID with its corresponding quantity. Try this code:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
Dictionary<string, string> tempList = new Dictionary<string, string>();
string quantity = "", prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID, quantity);
}
}
}
}
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(key);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(tempList[key]) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
}
Based on your examples above, tempList["1"] will produce "50", tempList["2"] will produce "77", and tempList["3"] will produce "90".

It is because you keep overriding variable "quantity" for each row you have the checkbox selected. If you want to store multiple values you need to use List<string> to store the quantities for each row where the checkbox is selected.
Something like below. Note: I haven't tested the code.
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> quantity = new List<string>();
prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity.Add(tbQuantity.Text);
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity[i];
}
}

you can do something like :
foreach (DataGridViewRow item in GV.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == true)
//here you get the rowcell value :
string val = item.Cells[1].Value.ToString();
//If you want to convert to a textbox :
TextBox textBox = (TextBox)item.Cells[1].Value;
}
where GV is the gridview Id
and checkbox is the 0 column and the value you might want to get is the 1 column

Related

How to check if the quantity inserted is greater than the new stock in my Datagridview Cell

I want to create a function that will check if the quantity inserted is greater than the new stock in my Datagridview Cell ["New Stock"] to prevent the data from execution.
double qty,totalprice,discount;
double.TryParse(txtqty.Text, out qty);
double.TryParse(txttotalprice1.Text, out totalprice);
double.TryParse(txtdiscount.Text, out discount);
//Boolean to check if he has row has been
bool Found = false;
if (dataGridView1.Rows.Count > 0)
{
// Check if the product Id exists with the same Price
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToString(row.Cells[0].Value) == cmbproductcode.Text && Convert.ToString(row.Cells[3].Value) == txtprice1.Text)
{
//Update the Quantity of the found row
row.Cells[5].Value = Convert.ToString(qty + Convert.ToInt16(row.Cells[5].Value));
row.Cells[7].Value = Convert.ToString(discount + Convert.ToInt16(row.Cells[7].Value)); //txtqty
row.Cells[8].Value = Convert.ToString(totalprice + Convert.ToInt32(row.Cells[8].Value)); //txttotalprice
Found = true;
getprice();
}
}
if (!Found)
{
//Add the row to grid view
getinfo();
}
}
else
{
//Add the row to grid view for the first time
getinfo();
}
public double prev;
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
string cellValue;
int i = e.RowIndex;
cellValue = dataGridView1.Rows[i].Cells[1].Value.ToString();
prev = Convert.ToDouble(cellValue);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string cellValue;
int i = e.RowIndex;
cellValue = dataGridView1.Rows[i].Cells[1].Value.ToString();
double cur = Convert.ToDouble(cellValue);
if(isvalid(prev,cur))
dataGridView1.Rows[i].Cells[1].Value = prev.ToString();
else
dataGridView1.Rows[i].Cells[1].Value = cellValue;
}
private Boolean isvalid(double pr,double cur)
{
return cur > pr ? false : true;
}

Gridview is sorting but Unable to add Gridview with ascending descending arrows..How to add?

This is my code for adding gridview with arrows..Gridview is sorting by ascending and descending but i am unable to add arrows.
protected void grdInformation_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row != null && e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
if (cell.HasControls())
{
LinkButton button = cell.Controls[0] as LinkButton;
HtmlGenericControl gv = new HtmlGenericControl("div");
Label lnkName = new Label();
lnkName.Text = button.Text;
if (button != null)
{
Image imageSort = new Image();
imageSort.ImageUrl = "~/images/asc.png";
if (grdInformation.SortExpression == button.CommandArgument)
{
if (grdInformation.SortDirection == SortDirection.Ascending)
{
imageSort.ImageUrl = "~/images/desc.png";
}
else
{
imageSort.ImageUrl = "~/images/asc.png";
}
}
gv.Controls.Add(lnkName);
gv.Controls.Add(imageSort);
button.Controls.Add(gv);
}
}
}
}
}
}}
Dono where i am going wrong , I have took an event for sorting , this is my code for sorting gridview it is working finee, but i am unable to add arrows to the girdview , the above i have tried but its not adding me arrows, how do i add arrows ??
i have tried some articles but i am unable to add arrows with ascending and descending , gridview is sorting when clicking on header rows , but need to display to the user that he can sort based on ascending arrows and descending arrows ...
protected void grdInformation_Sorting(object sender, GridViewSortEventArgs e)
{
if (CurrentSortExpression == e.SortExpression.ToString())
{
if (CurrentSortDirection == "asc")
CurrentSortDirection = "desc";
else
CurrentSortDirection = "asc";
}
else
{
CurrentSortExpression = e.SortExpression.ToString();
CurrentSortDirection = "asc";
}
if (e.SortExpression.Trim() == this.SortField)
{
this.sortDirection = (this.sortDirection == "DESC" ? "ASC" : "DESC");
}
else
{
this.sortDirection = "ASC";
}
ViewState["SortDirection"] = this.sortDirection;
this.SortField = e.SortExpression;
Bindinfo(GetInformation(ddlStatus.SelectedValue, ddlGroups.SelectedValue));
}
Please help ??
You can add the images like this.
System.Web.UI.WebControls.Image sortArrow = new System.Web.UI.WebControls.Image();
private void addSortImages()
{
int columnIndex = 0;
//set the image url
sortArrow.ImageUrl = "~/images/asc.png";
if (mySortDirection == SortDirection.Descending)
{
sortArrow.ImageUrl = "~/images/desc.png";
}
//check for rows in the gridview
if (GridView1.Rows.Count > 0)
{
//loop all the columns
foreach (DataControlFieldHeaderCell cell in GridView1.HeaderRow.Cells)
{
if (cell.ContainingField.SortExpression == mySortExpression)
{
columnIndex = GridView1.HeaderRow.Cells.GetCellIndex(cell);
}
}
//add the image to the correct header cell
GridView1.HeaderRow.Cells[columnIndex].Controls.Add(sortArrow);
}
}

ASP.NET removing DropDownList item inside repeater?

I don't know if I am allowed to post such a specific issue here.
The scenario is that I have a Product that has a many to many relationship with Category.
Means one product may belong to multiple categories and a category may have multiple products. Now on the form I have provide a dropdown along with a button that says add another category and when I click on that button another dropdown should appear below that first dropdown. and the selected item of the previous dropdown must be remove from the dropdown items.
Below is my code of the dropdown's repeater and the two buttons mentioned.
protected void btnAddAnotherCategory_Click(object sender, EventArgs e)
{
List<int> selectedIndices = new List<int>();
foreach (RepeaterItem item in rptCategories.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory");
int selectedIndex = ddlCategory.SelectedIndex;
selectedIndices.Add(selectedIndex);
}
}
ViewState["objSelectedIndices"] = selectedIndices;
rptCategories_DataSource("add", false);
}
protected void btnRemoveCategory_Click(object sender, EventArgs e)
{
List<int> selectedIndices = new List<int>();
foreach (RepeaterItem item in rptCategories.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory");
int selectedIndex = ddlCategory.SelectedIndex;
selectedIndices.Add(selectedIndex);
}
}
ViewState["objSelectedIndices"] = selectedIndices;
rptCategories_DataSource("remove", false);
}
protected void rptCategories_DataSource(string editCommand, bool pageLoad)
{
switch (editCommand)
{
case "add":
if (ViewState["categoriesCount"] == null)
{
List<Category> count = new List<Category>();
count.Add(new Category());
ViewState["categoriesCount"] = count;
}
if (!pageLoad)
{
List<Category> count = (List<Category>)ViewState["categoriesCount"];
count.Add(new Category());
ViewState["categoriesCount"] = count;
}
List<Category> objCategories = (List<Category>)ViewState["categoriesCount"];
objCategories = objCategories.Where(x => x.StatusID != 3).ToList();
rptCategories.DataSource = objCategories;
rptCategories.DataBind();
break;
case "remove":
if (((List<Category>)ViewState["categoriesCount"]).Count > 1)
{
List<Category> count = (List<Category>)ViewState["categoriesCount"];
count.Remove(count.Last());
count = count.Where(x => x.StatusID != 3).ToList();
ViewState["categoriesCount"] = count;
rptCategories.DataSource = count;
rptCategories.DataBind();
}
break;
}
}
protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Category objCategory = (Category)e.Item.DataItem;
DropDownList ddlCategory = (DropDownList)e.Item.FindControl("ddlCategory");
ddlCategory.DataSource = new CategoryBLL().GetAllCategoriesWithStatus();
ddlCategory.DataTextField = "Name";
ddlCategory.DataValueField = "ID";
ddlCategory.DataBind();
if (objCategory.CategoryID != null)
ddlCategory.SelectedValue = objCategory.CategoryID.ToString();
if (ViewState["objSelectedIndices"] != null)
{
List<int> objSelectedIndices = (List<int>)ViewState["objSelectedIndices"];
if (objSelectedIndices.Count > e.Item.ItemIndex)
ddlCategory.SelectedIndex = objSelectedIndices.ElementAt(e.Item.ItemIndex);
}
if (e.Item.ItemIndex < ((List<Category>)rptCategories.DataSource).Count - 1)
{
ddlCategory.Enabled = false;
}
btnAddAnotherCategory.Visible = true;
btnRemoveCategory.Visible = true;
if (rptCategories.Items.Count < 1)
{
btnRemoveCategory.Visible = false;
}
if (rptCategories.Items.Count >= new CategoryBLL().GetAllCategoriesWithStatus().Count - 1)
{
btnAddAnotherCategory.Visible = false;
}
}
The StatusID mentioned in the code is to determine the deleted products as I am not ACTUALLY deleting the Product rather only setting its StatusID
Now the problem is that my code works fine with the above statements but as you can see it does not remove the selected items from the dropdown. The dropdown's are required to be populated from a single table everytime. The tricky part is removing the selecteditems in the previous repeateritems dropdownlist.
Any solution would be welcomed.

How to change the index of previous selected Dropdownlist?

I have gridview with template field of dropdownlist in each row.when i select any value from dropdownlist it will change color of 3rd row below than it.But when i click on another dropdownlist it is changing the color of 3rd row below than it but the index of previous dropdownlist is not changed to 0 i.e"Select".it is still showing the value selected in last dropdown list.I just want when i click on a dropdownlist ,all other dropdownlist should be indexed to 0 i.e "Select" except one which i have clicked.
I am doing following in Selectedindexchange event of dropdownlist:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
int g1 = gvRow.RowIndex;
GridView1.Rows[g1].BackColor = Color.White;
}
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
int pp = GridView1.Rows.Count;
GridView1.Rows[g].BackColor = Color.Red;
}
}
Thanks in advance.
Just use DropdownName.ClearSelection() for each of your other dropdown except the one where you are calling Selectedindexchange event.
Maybe something like this:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
foreach (GridViewRow gvRow in GridView1.Rows)
{
gvRow.BackColor = Color.White;
if (gvRow.FindControl("nameOfTheDropdown") != null && gvRow.RowIndex != current_row_index)
{
((DropDownList)gvRow.FindControl("nameOfTheDropdown")).SelectedIndex = 0;
}
}
GridView1.Rows[g].BackColor = Color.Red;
}
Regards

checkBox in gridView

i am using checkbox in gridview..to get the checkbox id i am using the following code..
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows.Cells[1].Text;
idCollection.Add(strID);
}
}
}
BUT THE KEYWORD "CELLS"..do not support..i am getting an error.."System.Web.UI.WebControls.GridViewRowCollection' does not contain a definition for 'Cells' "
This is the way you have to check
foreach (GridViewRow grRow in grdACH.Rows)
{
CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
if (chkItem.Checked)
{
strID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
}
}
That's correct; the GridViewRowCollection class does not contain either a method or a property with the name Cells. The reason that matters is that the Rows property of the GridView control returns a GridViewRowCollection object, and when you call GridView1.Rows.Cells, it is searching for a Cells property on the GridViewRowCollection object returned by the Row property.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
foreach (GridViewRow rowitem in GridView1.Rows)
{
CheckBox chkDelete = (CheckBox)rowitem.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = rowitem.Cells[1].Text;
idCollection.Add(strID);
}
}
}

Categories

Resources