Grid view row command is firing after every second click - c#

I've shopping cart in grid view. The grid is in update panel with update mode always. The grid view is itself in a user control and this user control renders in a child page (GridView --> User Control --> Child aspx page --> master page). Whenever I click on any button to modify cart the gridview row command not fires first time but when I again click on the button second time the row command fires correctly. Now I don't know why the row command event is not firing on first click and it is firing only on every even click (second click).
ASP:
<asp:GridView ID="GVCart" runat="server" AutoGenerateColumns="False" OnRowCommand="CartUpdate">
<Columns>
<asp:BoundField DataField="Product_Name" HeaderText="Product Name">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="Button3" runat="server" CommandArgument='<%# Eval("Product_ID") %>'
CommandName="DecreseCartQty" Height="20px" ToolTip="Minus" AlternateText="+" />
<asp:ImageButton ID="ImageButton1" runat="server" CommandArgument='<%# Eval("Product_ID") %>'
CommandName="IncreaseCartQty" Height="20px" ToolTip="Add" AlternateText="-" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="ABC" runat="server" Text='<%# Eval("ItemQTY")+" * "+Eval("Price")+" = "+Eval("TotalPrice") %> '></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="Button4" runat="server" CommandArgument='<%# Eval("Product_ID") %>' CommandName="Remove" ToolTip="Cancel"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#: (in user control)
protected void CartUpdate(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "IncreaseCartQty")
{
int ProductId = Convert.ToInt32(e.CommandArgument.ToString());
DataTable CartDT = (DataTable)Session["cart"];
for (int i = 0; i < CartDT.Rows.Count; i++)
{
if (CartDT.Rows[i]["Product_ID"].ToString() == ProductId.ToString())
{
CartDT.Rows[i]["ItemQTY"] = Convert.ToInt32(CartDT.Rows[i]["ItemQTY"]) + 1;
CartDT.Rows[i]["TotalPrice"] = Convert.ToInt32(CartDT.Rows[i]["Price"]) * Convert.ToInt32(CartDT.Rows[i]["ItemQTY"]);
//Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
}
if (e.CommandName == "DecreseCartQty")
{
int ProductId = Convert.ToInt32(e.CommandArgument.ToString());
DataTable CartDT = (DataTable)Session["cart"];
for (int i = 0; i < CartDT.Rows.Count; i++)
{
if (CartDT.Rows[i]["Product_ID"].ToString() == ProductId.ToString())
{
if (Convert.ToInt32(CartDT.Rows[i]["ItemQTY"]) > 1)
{
CartDT.Rows[i]["ItemQTY"] = Convert.ToInt32(CartDT.Rows[i]["ItemQTY"]) - 1;
CartDT.Rows[i]["TotalPrice"] = Convert.ToInt32(CartDT.Rows[i]["Price"]) * Convert.ToInt32(CartDT.Rows[i]["ItemQTY"]);
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
}
}
if (e.CommandName == "Remove")
{
int ProductId = Convert.ToInt32(e.CommandArgument.ToString());
DataTable CartDT = (DataTable)Session["cart"];
for (int i = 0; i < CartDT.Rows.Count; i++)
{
if (CartDT.Rows[i]["Product_ID"].ToString() == ProductId.ToString())
{
CartDT.Rows.RemoveAt(i);
//Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
}
}
Can anyone tell me what wrong I am doing. Your answer will be great help for me.
Thanks in advance.

It is behaving properly. You should rebind the gridview after CartUpdate so that another post back is not required.
just add these lines after
if (e.CommandName == "Remove")
{
int ProductId = Convert.ToInt32(e.CommandArgument.ToString());
DataTable CartDT = (DataTable)Session["cart"];
for (int i = 0; i < CartDT.Rows.Count; i++)
{
if (CartDT.Rows[i]["Product_ID"].ToString() == ProductId.ToString())
{
CartDT.Rows.RemoveAt(i);
//Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
}
DataTable CartDT = (DataTable)Session["cart"];
gridview1.datasource=CartDT ;
gridview1.databind();

Checkout this answer, I think it will solve your problem. If you have your grid view in user control this issue can arise. I had a same issue when I had my grid view in a user control.

Related

gridview can't add after clearing

I am using entity framework and taking my datas from database and fill my gridview with them.Datas selected by user from a treview.Simply, user selects a data from treeview and I put it to gridview. Lastly I have a button for clearing the gridview. Here is my aspx:
<div id="divPrint" style="background-color: white" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<p style="text-align:center">HDCVI KAMERA FİYAT TEKLİFİDİR</p>
<asp:GridView ID="GridViewHdcvi" runat="server" DataSourceID="EntityDataSourceHdcvi" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ÜRÜN VE DETAYLARI">
<ItemStyle Width="400px" />
<ItemTemplate>
<div style="color: red" class="text-center"><%#Eval("UrunAdi") %></div>
<%#Eval("UrunDetay") %>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="ÜRÜN GÖRSELİ" DataImageUrlField="UrunResim"></asp:ImageField>
<asp:TemplateField HeaderText="BİRİM FİYAT">
<ItemTemplate>
<%#Eval("UrunFiyati") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ADET">
<ItemTemplate>
<asp:TextBox ID="txtAdet" runat="server" Width="40px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:Button ID="btnListiSifirla" runat="server" Text="Listeyi Sıfırla" CssClass="btn btn-danger" OnClick="btnListiSifirla_Click" />
And my codebehind:
static List<string> urunList = new List<string>();
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
string id = TreeView1.SelectedValue;
urunList.Add(id);
listeyiDoldur();
}
protected void listeyiDoldur()
{
if (urunList.Count == 0)
{
failDiv.Visible = true;
}
else
{
string query = "SELECT UrunTable.UrunAdi, UrunTable.UrunFiyati, UrunTable.UrunResim, UrunTable.UrunKategori, UrunTable.UrunDetay FROM UrunTable WHERE ";
foreach (var val in urunList)
{
if (val.Equals(urunList[urunList.Count - 1]))
{
query += "UrunTable.UrunId = " + val;
}
else
{
query += "UrunTable.UrunId = " + val + " || ";
}
}
EntityDataSourceHdcvi.CommandText = query;
divPrint.Visible = true;
btnListiSifirla.Visible = true;
}
}
protected void btnListiSifirla_Click(object sender, EventArgs e)
{
urunList.Clear();
btnListiSifirla.Visible = false;
Page_Load(null,EventArgs.Empty);
}
I can successfully display selected datas in gridview and clear them when button is pressed. Here is the problem: After clearing the gridview I can't add the last added item again.For example if I add item1,item2 and item3 in this order,after clearing the gridview I can't add item3. I can add item1 or item2, then item3. I can't add item firstly which I added last before clearing. I tried clearing gridview in button's onClick and tried other lots of things but nothing gave any result. Thanks for your time.

Textboxes Causing Problems in ASP.NET C# SQL

I am using a nested Gridview(I have 5 Nested Gridviews).
I have applied a Regular Field validator for these Gridviews.
But once I click the button, commas are generated in the textbox. Due to that whenever I click the button, all the validation get fired.
I have researched lots of articles but have not found one related to this.
Here is the image for the Gridview with the commas generated in the textbox:
HTML Code Part
<%-- First Gridview--%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="gvstyling gridview_width_60" ShowHeaderWhenEmpty="true" EmptyDataText="Record(s) Not Found!"
DataKeyNames="locality" ShowHeader="false" OnRowDataBound="gvLocality_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlCompanyName" runat="server" Style="display: none">
<%-- Second Gridview --%>
<asp:GridView ID="gvCompanyName" ShowHeader="false" ShowHeaderWhenEmpty="false" CssClass="gvstyling gridview_width_100"
OnRowDataBound="gvCompanyName_RowDataBound" runat="server"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="hfRetailer_Id" Value='<%# Eval("retailer_id") %>' runat="server"></asp:HiddenField>
<asp:HiddenField ID="hfLocality" Value='<%# Eval("locality") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lbl" Visible="false" Text='<%# Eval("retailer_id") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlSellOrderNo" runat="server" Style="display: none">
<%-- Third Gridview --%>
<asp:GridView ID="gvSellOrderNo" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server" OnRowDataBound="gvSellOrderNo_RowDataBound"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="hf_SellOrderNo" Value='<%# Eval("sell_order_no") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lblSellOrderNo" Visible="false" Text='<%# Eval("sell_order_no") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlProductDetails" runat="server" Style="display: none">
<%-- fourth Gridview --%>
<asp:GridView ID="gvProductDetails" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server" OnRowDataBound="gvProductDetails_RowDataBound"
AutoGenerateColumns="false" EmptyDataText="No Record(s) Found!">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" Value='<%# Eval("sell_order_no") %>' runat="server"></asp:HiddenField>
<asp:HiddenField ID="hfProductId" Value='<%# Eval("product_id") %>' runat="server"></asp:HiddenField>
<asp:Label ID="lblProductId" Visible="false" Text='<%# Eval("product_id") %>' runat="server"></asp:Label>
<img alt="" style="cursor: pointer" src="../images/plus.png" />
<asp:Panel ID="pnlWarehouseDetails" runat="server" Style="display: none">
<%-- fifth Gridview--%>
<asp:GridView ID="gvWarehouseDetails" ShowHeader="false" ShowHeaderWhenEmpty="false"
CssClass="gvstyling gridview_width_100" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblWarehouseId" Text='<%# Eval("c_warehouse_id") %>' Visible="false" runat="server"></asp:Label>
<%# Eval("warehouse_name") %> (<%# Eval("qty") %>)
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- fifth Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("product_name") %> (<%# Eval("qty") %>)
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- fourth Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("sell_order_no") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- Third Gridview --%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Business Name">
<ItemTemplate>
<%# Eval("business_name") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- Second Gridview--%>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="gv_item_bg">
<ItemTemplate>
<asp:Label ID="lblLocality" runat="server" Text=' <%# Eval("locality") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- First Gridview --%>
Code Behind File
//Filling Shipping Company Name
private void FillShippingCompanyName()
{
try
{
ArrayList arr = new ArrayList();
cm.ds.Clear();
cm.sp_dataset_execute("spdisplay_Shipping_Comany_Name", arr);
ddlCompanyName.DataSource = cm.ds;
ddlCompanyName.DataValueField = "shipping_code";
ddlCompanyName.DataTextField = "shipping_name";
ddlCompanyName.DataBind();
ddlCompanyName.Items.Insert(0, new ListItem("---- Select Shipping Company ----", "0"));
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-FillShippingCompanyName()");
}
finally
{
cm.con.Close();
}
}
private void FillLocality()
{
try
{
cm.ds.Clear();
ArrayList arr = new ArrayList();
cm.sp_dataset_execute("spDisplay_Locality", arr);
gvLocality.DataSource = cm.ds;
gvLocality.DataBind();
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-FillLocality()");
cm.con.Close();
}
finally
{
cm.con.Close();
}
}
//Locality Gridview Row Databound (Level 1 Grdview)
common cm1 = new common();
protected void gvLocality_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Locality = gvLocality.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvCompanyName = e.Row.FindControl("gvCompanyName") as GridView;
cm1.ds.Clear();
//Binding Company Gridview
ArrayList arr1 = new ArrayList();
arr1.Add("#locality|" + Locality + "");
cm1.sp_dataset_execute("spDisplayCompanyName", arr1);
gvCompanyName.DataSource = cm1.ds;
gvCompanyName.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Recent_activity-gvRecentActivityOuter_RowDataBound()");
cm1.con.Close();
}
finally
{
cm1.con.Close();
}
}
//Comapny Name Gridview Row Databound (Level 2 Grdview)
common cm2 = new common();
protected void gvCompanyName_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string RetailerId = ((HiddenField)e.Row.FindControl("hfRetailer_Id")).Value;
GridView gvSellOrderNo = e.Row.FindControl("gvSellOrderNo") as GridView;
string Locality = ((HiddenField)e.Row.FindControl("hfLocality")).Value;
cm2.ds.Clear();
//Binding Company Gridview
ArrayList arr = new ArrayList();
arr.Add("#retailer_id|" + RetailerId + "");
arr.Add("#locality|" + Locality + "");
cm2.sp_dataset_execute("spDisplay_SellOrderNo", arr);
gvSellOrderNo.DataSource = cm2.ds;
gvSellOrderNo.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-Page_Load()");
cm2.con.Close();
}
finally
{
cm2.con.Close();
}
}
//Sell Order Gridview Row Databound (Level 3 Grdview)
common cm3 = new common();
protected void gvSellOrderNo_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string SellOrderNo = ((HiddenField)e.Row.FindControl("hf_SellOrderNo")).Value;
GridView gvProductDetails = e.Row.FindControl("gvProductDetails") as GridView;
FillProductDetails(gvProductDetails, SellOrderNo);
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-gvSellOrderNo_RowDataBound()");
cm3.con.Close();
}
finally
{
cm3.con.Close();
}
}
private void FillProductDetails(GridView gvProductDetails, string SellOrderNo)
{
cm3.ds.Clear();
//Product Details Gridview
ArrayList arr = new ArrayList();
arr.Add("#sell_order_no|" + SellOrderNo + "");
cm3.sp_dataset_execute("spDisplay_ProductDetails", arr);
gvProductDetails.DataSource = cm3.ds;
gvProductDetails.DataBind();
}
//Product Details Gridview Row Databound (Level 4 Grdview)
common cm4 = new common();
protected void gvProductDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ProductID = ((HiddenField)e.Row.FindControl("hfProductId")).Value;
string SellOrderNo = ((HiddenField)e.Row.FindControl("HiddenField1")).Value;
GridView gvWarehouseDetails = e.Row.FindControl("gvWarehouseDetails") as GridView;
cm4.ds.Clear();
//Product Details Gridview
ArrayList arr = new ArrayList();
arr.Add("#product_id|" + ProductID + "");
arr.Add("#sell_order_no|" + SellOrderNo + "");
cm4.sp_dataset_execute("spDisplay_WarehouseDetails", arr);
gvWarehouseDetails.DataSource = cm4.ds;
gvWarehouseDetails.DataBind();
}
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-gvProductDetails_RowDataBound()");
cm4.con.Close();
}
finally
{
cm4.con.Close();
}
}
//Submit Button
protected void btnSubmit_Click1(object sender, EventArgs e)
{
try
{
cm.ds.Clear();
//--Insert Query for Rs_Shipping_Order_Details
string ShippingCode = "SHO" + DateTime.Now.ToString("yyyyMMddHHmmss");
string ShippingGroup = "SG" + DateTime.Now.ToString("yyyyMMddHHmmss");
ArrayList arr = new ArrayList();
arr.Add("#shipping_code|" + ShippingCode + "");
arr.Add("#shipping_Company_code|" + ddlCompanyName.SelectedValue + "");
arr.Add("#is_shipping_delivered|0");
cm.sp_execute("spInsert_Shipping_Order_Detail", arr);
//Locality for loop
for (int i = 0; i < gvLocality.Rows.Count; i++)
{
GridView gvCompanyName = gvLocality.Rows[i].FindControl("gvCompanyName") as GridView;
//Company for loop
for (int j = 0; j < gvCompanyName.Rows.Count; j++)
{
GridView gvSellOrderNo = gvCompanyName.Rows[j].FindControl("gvSellOrderNo") as GridView;
string RetailerId = ((Label)gvCompanyName.Rows[j].FindControl("lbl")).Text;
//Sell Order for loop
for (int k = 0; k < gvSellOrderNo.Rows.Count; k++)
{
//Product Details Gridview
GridView gvProductDetails = gvSellOrderNo.Rows[k].FindControl("gvProductDetails") as GridView;
string SO = ((Label)gvSellOrderNo.Rows[k].FindControl("lblSellOrderNo")).Text;
int retailer_Id = Convert.ToInt32(RetailerId);
//Product Details for loop
for (int l = 0; l < gvProductDetails.Rows.Count; l++)
{
//Warehouse Details Gridview
GridView gvWarehouseDetails = gvProductDetails.Rows[l].FindControl("gvWarehouseDetails") as GridView;
string ProductId = ((Label)gvProductDetails.Rows[l].FindControl("lblProductId")).Text;
//Warehouse Details for loop
for (int m = 0; m < gvWarehouseDetails.Rows.Count; m++)
{
TextBox txtQty = gvWarehouseDetails.Rows[m].FindControl("txtQty") as TextBox;
string LastValue = txtQty.Text.Split(',').Last();
if (String.IsNullOrEmpty(LastValue) == false)
{
string Warehouse_Id = ((Label)gvWarehouseDetails.Rows[m].FindControl("lblWarehouseId")).Text;
int warehouse_id = Convert.ToInt32(Warehouse_Id);
string Qty = LastValue;
//Insert Query for Rs_Shipping_Detail_Mapping
ArrayList arr1 = new ArrayList();
arr1.Add("#shipping_order_code|" + ShippingCode + "");
arr1.Add("#retailer_id|" + retailer_Id + "");
arr1.Add("#sell_order_no|" + SO + "");
arr1.Add("#product_id|" + ProductId + "");
arr1.Add("#c_warehouse_id|" + warehouse_id + "");
arr1.Add("#shipping_group|" + ShippingGroup + "");
arr1.Add("#qty|" + Qty + "");
common cm1 = new common();
cm1.sp_execute("spInsert_Shipping_Detail_Mapping", arr1);
////Generating Pdf for Each Sell Order
//if (m == gvWarehouseDetails.Rows.Count - 1)
//{
// Generate_SellOrderWise_PDf(SO, ShippingCode, ShippingGroup);
//}
}
}
}
}
}
}
Response.Redirect("../final-shipping-order/?SG=" + ShippingGroup, false);
}
catch (Exception ex)
{
ErrHandler.WriteError(ex.Message.ToString(), "Shipping-Order-btnSubmit_Click1()");
cm4.con.Close();
}
finally
{
cm4.con.Close();
}
}
Question :
1. How do I remove the commas from the textboxes?
2. Reason for these commas? (Why are the commas being generated on the button click?)
3. Limit for the Nested Gridview ?
Any help will be appreciated.
When you have duplicate form field names, the values are concatenated together with commas.
So, for example, if you have the following..
<input type="text" name="name" value="">
<input type="text" name="name" value="">
.. your resulting value on Request.Form postback looks like this:
name=,,
That's what's happening.
Here are a few possible solutions to your problem, though I have not tested any of them :)
1) UpdatePanel
From reading, it seems that if you create an UpdatePanel for the offending grid control (<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>) , it removes this problem. Again, I have not tested this
2) Changing DataBind() behavior during Page_Load()
So...
page_load()
{
if(!isPostBack())
{
// DataBind normally
myGridview.DataBind();
}
else
{
//Some intelligent way to remove commas before binding
}
}
... But that doesn't change the fact that the ,,,values are being posted in the first place. And so, if your primarily concerned with the end aesthetic and not behavior, you can just use JS to strip out the commas (as previously suggested hinted at.)
3) JS - Get Rid of the Commas:
(as suggested here)
<script type="text/javascript">
$("[src*=plus]").live("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
$("input", $(this).closest("tr").next()).each(function () {
this.value = this.value.substring(',', '');
});
});
$("[src*=minus]").live("click", function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
});
</script>
Hope this helps :)
[Edit] - Validation
I would fire off validation using the .keydown() event. In your case, it might look something like this:
// Bind to each input with id='txtQty', in each row, in the "gridview" with id='gvWarehouseDetails'
$("#gvWarehouseDetails tr input[id*='txtQty']").each(function () {
$(this).keydown(function (event) { // <-- specifies the specific input
// Validation logic goes here...
});
});
The Ajax Control Toolkit is a viable solution, however support for it has become non-existent. I'm assuming there is a level of dynamic control on that field. In essence, the grid will display it at certain instances?
Either way, you could add a specific class to the field:
<asp:Textbox id="txtContent" runat="server" CssClass="Validator">
Essentially when the grid adds all of these fields to your page, they'll all have the Validator class. So you can write JavaScript to actually strip the character out of the field, example:
$('.Validator').on('blur', function() {
$(this).replace(',', '');
});
As soon as the focus changes, that field will remove the , from the field as soon as the mouse leaves the , will be removed from the field.
That is one approach, countless other options do exist as well to accomplish this. This solution is pretty easy, agile, and light so it should be adequate.
Update:
The solution I chose shouldn't require a loop over those fields. Simply because blur triggers whenever a change or focus is lost on that field. Since you mentioned the , appears when the user clicks in the field. Otherwise you could do validation on all the fields. All you simply would need to do:
$('.Validator').each(function() {
// Will iterate through each field.
});
So you could essentially use JavaScript yourself to validate those fields, or use a simple library such as Valid8 which will do all client-side validation. No postback, all done client side before sent to the server to process.
Avoid:
Update Panel - These are quite a pain and incredibly inefficient. The way they work basically is by taking your entire page and storing it memory then does an Ajax request and refreshes your page and pulls all the contents out of memory to place on the page. Additionally it makes working with the Asp.Net Page Life Cycle incredibly difficult.
Hardik, how is txtQty.Text bound at first?
Does it come as an empty text box?
You using the code string LastValue = txtQty.Text.Split(',').Last(); to try go get rid of this comma values inserted or the values bound come with commas? I mean, you using the same UI culture from values in the database and the app or do you have to format it before displaying it?
I Don't know what is happening in your code. But If you want to get rid of Comma (',') then I should suggest one thing to you.
Add a reference of AjaxControlToolKit and register it in your aspx page as shown below:
<%# Register TagPrefix="ajaxToolkit" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit, Version=[VersionNumber], Culture=neutral, PublicKeyToken=[TokenNumber]" %>
Or You can refer How to install AJAX Control toolkit
Once you have installed AJAX Control Toolkit, Go to your page and in your grid TemplateField, below TextBox txtQty, add FilteredTextBoxExtender as shown below:
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender runat="server" InvalidChars="," FilterMode="InvalidChars" TargetControlID="txtQty" />
</ItemTemplate>
</asp:TemplateField>
By Adding FilterTextBoxExtender, It will not allow characters to be inserted which are mentioned as InvalidChars to the textbox 'txtQty'.

Validators array work only first time with asp.net gridview IN GOOGLE CHROME?

I noticed it works perfectly in Internet explorer, but not in Google Chrome!
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button saveBtn = (Button)e.Row.FindControl("btnSave");
CompareValidator validatorNow = (CompareValidator)e.Row.FindControl("DateValidator1");
saveBtn.ValidationGroup = "mygroupnow" + e.Row.RowIndex;
validatorNow.ValidationGroup = "mygroupnow" + e.Row.RowIndex;
saveBtn.Attributes.Add("onclick", "AllValidators('"+ e.Row.RowIndex + "');");
}
}
I have a gridview with a template, one column has a textbox with validator, and there's a column with a 'save' submit button. I give them a mutual validationGroup name using their row index. I also have update panel on my page, so until now the only way I could disable/enable a button after validating was with javascript. so I created the following method, to check on client click if the validator is valid:
function AllValidators(index) {
var currentValidationGroup = 'mygroupnow' + index;
for (i = 0; i < Page_Validators.length; i++) {
if (i == index) { if (Page_Validators[i].validationGroup == currentValidationGroup) { ValidatorValidate(Page_Validators[i], currentValidationGroup);
if (Page_Validators[i].isvalid) { alert('Validated!'); } else {alert('not Valid'); } } }
}
}
Now, this works great, but only for the first index... index 0, when i = 0, then the alerts really go off according to if it is validated or not, but for the other gridview rows, it just always returns 'Validated', even when it is not. I don't understand whats wrong, the code clearly works since it works the first time, so why not the others too?
and the gridview code :
<asp:GridView ID="GridView1" runat="server" DataSourceID="ds_OpenOrders" OnSelectedIndexChanged="Grid_SelectedIndexChanged"
onrowcreated="GridView1_RowCreated" CssClass="gridBx"
onprerender="GridView1_PreRender" onrowupdated="GridView1_RowUpdated"
onrowupdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
onrowdatabound="GridView1_RowDataBound" CellPadding="3" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" AllowPaging="true" DataKeyNames ="RschEstTime,DRNLoanNumber" PageSize="8" Width="859px" ShowFooter="True">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:TemplateField HeaderText="Est Return Date" SortExpression="RschEstDate" HeaderStyle-VerticalAlign="Top">
<ItemTemplate>
<asp:TextBox ID="txtReturnDate1" runat="server" TabIndex="1" Text='<%# Bind("RschEstDate", "{0:MM/dd/yyyy}") %>' Width="70px" AutoPostBack="True" OnTextChanged="GlobalControl_Changed"></asp:TextBox>
<asp:CompareValidator ID="DateValidator1" runat="server" Type="Date" Operator="DataTypeCheck" ErrorMessage="Wrong Format" ControlToValidate="txtReturnDate1" Text="*" Display="Static" EnableClientScript="true"></asp:CompareValidator>
</ItemTemplate>
<asp:TemplateField
<ItemTemplate>
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Update" CausesValidation="true" OnClick="MyBtnClick"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
I've also tried doing simpler action in javascript, without the whole loop of Page_validators, and just tried this :
function NextTry(validationName) {
if (Page_ClientValidate(validationName)) { alert('yesss'); } else { alert('noooo'); }
}
or
function NextTry(index) {
if(Page_ClientValidate('mygroupnow' + index)) { alert('Valid!');} else { alert('Not Valid'); } }
}
and again, same problem, it works for the first row, index 0, it alerts really according to that row validation, for the others, it always returns 'Valid', even when it is not.
I haven't tested it. But, a similar code works for my project.
function AllValidators(index) {
var currentValidationGroup = 'mygroupnow' + index;
$("#<%=gdRows.ClientID%> tr").each(function() {
for (i = 0; i < Page_Validators.length; i++) {
if (i == index) { if (Page_Validators[i].validationGroup == currentValidationGroup) { ValidatorValidate(Page_Validators[i], currentValidationGroup);
if (Page_Validators[i].isvalid) { alert('Validated!'); } else {alert('not Valid'); } } }
}
}
}
loop through your gridview rows individually and check the validators.. A similar example is addressed here.

How to Uncheck Select All Checkbox when one checkbox is Unchecked

I have a checkbox named Select All. When I click this then all other check box inside my Gridview is Checked. But I want when anyone of the checkbox inside the grid will be unchecked then this Select All Checkbox will automatically uncheck. Is there anyone who can help me on this Please?
Thank you.
function SelectheaderCheckboxes(headerchk) {
debugger
var gvcheck = document.getElementById('gvdetails');
var i;
//Condition to check header checkbox selected or not if that is true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
<asp:GridView ID="gvdetails" runat="server" DataSourceID="dsdetails" onrowdatabound="gvdetails_RowDataBound" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectheaderCheckboxes(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can do this on the client or the server side
Client side using javascript/jquery
As the checkboxes are added dynamically you will need to use the on method to bind the checkboxes to the function and fire it when their state changes.
$(document).ready(function() {
$(".checkbox").on("change", function() {
if(!$(this).is(":checked")){
$(".selectAll").prop('checked', false);
}
});
});
Here is a jsFiddle with a full functioning select All that will:
Select All / Deselect All
Untick Select All when one of the checkboxes is unticked
Tick select All when all checkboxes are ticked
Server side
use an event handler to on a postback(ajax) when a checkbox is unticked and loop through all checkboxes and untick them
Font-end uses ajax to do a partial postback to update the gridview.
the select all checkbox and gridview checkboxes will trigger the postback.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvCheckBoxes" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="cbCheckBox" OnCheckedChanged="CheckBoxChanged" AutoPostBack="true" runat="server" />
</ItemTemplate>
/asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbSelectAll"/>
</Triggers>
</asp:UpdatePanel>
Code Behind
The select All check box event handler loops through the gridview and finds the checkboxes.
It ticks them if the select all checkbox is ticked otherwise it unticks them
The gridview checkbox event handler loops through the checkboxes and sets a flag to determine if it should tick or untick the select all checkbox. It exists the loop if any of the checkboxes are not ticked as select all must therefore be unticked as well
public void SelectAll (Object sender, Eventargs e)
{
foreach (var row in grid.Rows)
{
var checkBox = (CheckBox)row.FindControl("cbCheckBox");
checkBox.Checked = cbSelectAll.Checked;
}
}
public void CheckBoxChanged(Object sender, Eventargs e)
{
var isSelectAll = true;
foreach (var row in grid.Rows)
{
var checkBox = (CheckBox)row.FindControl("cbCheckBox");
if(!checkBox.Checked)
{
isSelectAll = false;
break;
}
}
cbSelectAll.Checked = isSelectAll;
}
Best way I can think of is to convert the GridView's CheckBoxField to a TemplateField. Then wire up the new asp:CheckBox in your TemplateField to the CheckedChanged event. In your code-behind, you handle the CheckedChanged event, then when any of the checkboxes change to unchecked, you can toggle your "check all" checkbox.
Look at this code. hope this will help you
<div>
<asp:CheckBox ID="chkSelectAll" runat="server" />
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" oncheckedchanged="chkSelect_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
bool isFound = false;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect.Checked == false)
{
isFound = true;
break;
}
}
if (isFound)
{
chkSelectAll.Checked = false;
}
else
{
chkSelectAll.Checked = true;
}
}
The following code should work. I tested it.
Javascript:
<script type="text/javascript">
function OnOneCheckboxSelected(chkB) {
var IsChecked = chkB.checked;
var Parent = document.getElementById('gridFileList');
var cbxAll;
var items = Parent.getElementsByTagName('input');
var bAllChecked = true;
for (i = 0; i < items.length; i++) {
if(items[i].id.indexOf('cbxSelectAll') != -1){
cbxAll = items[i];
continue;
}
if (items[i].type == "checkbox" && items[i].checked == false) {
bAllChecked = false;
break;
}
}
cbxAll.checked = bAllChecked;
}
function SelectAllCheckboxes(spanChk) {
var IsChecked = spanChk.checked;
var cbxAll = spanChk;
var Parent = document.getElementById('gridFileList');
var items = Parent.getElementsByTagName('input');
for (i = 0; i < items.length; i++) {
if (items[i].id != cbxAll.id && items[i].type == "checkbox") {
items[i].checked = IsChecked;
}
}
}
</script>
ASPX Markup:
<asp:TemplateField HeaderText="Select">
<HeaderTemplate>
<asp:CheckBox ID="cbxSelectAll" OnClick="javascript:SelectAllCheckboxes(this);" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox OnClick="javascript:OnOneCheckboxSelected(this);" ID="cbxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Above code I modifiyed it, if user unchecked the child rows of grid. grid header will automatically uncheck.
<script type="text/javascript">
function UncheckHeader(headerchk) {
var gvcheck = document.getElementById('gvdetails');
var inputs = gvcheck.rows[0].getElementsByTagName('input');
inputs[0].checked = false;
}
function SelectAll(headerchk) {
var gvcheck = document.getElementById('gvdetails');
var i;
// if true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
</script>
<asp:GridView ID="gvdetails" runat="server" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectAll(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server" onclick="javascript:UncheckHeader(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
more details here

how to search a control in an asp.net gridview and access it?

I have a gridview as :
<asp:GridView ID="gvAppRejProfiles" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Resumes
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnResumes" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i have a list of resume names (string format) that i want to add as the text of the linkbutton "lbtnResumes" for all the resume names that i have in a string array.
make use of FindControl() mehod ....to search control
void gvAppRejProfiles_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton bl =
(LinkButton)e.Row.FindControl("lbtnResumes");
}
}
for (int count = 0; count < gvAppRejProfiles.Rows.Count; count++)
{
LinkButton lbtnResumes = (LinkButton)gvAppRejProfiles.Rows[count].FindControl("lbtnResumes");
if (lbtnResumes.Text == "resume")
{
// Store and perform any operation
}
}

Categories