asp.net multiple gridviews - not display data - c#

I have two GridView and i want display data from two DataTables. There is my GridViews code in aspx file :
<div class="col-sm-5">
<div class="col-sm-6">
<asp:GridView ID="gvSource" runat="server" ShowHeaderWhenEmpty="true" CssClass="drag_drop_grid GridSrc" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Miejsca (wybór)</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNazwa" runat="server" Text='<%# Eval("Nazwa") %>' />
<asp:HiddenField ID="IDVal" ClientIDMode="Static" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="col-sm-6 pull-left">
<asp:GridView ID="gvDest" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No data to display" CssClass="drag_drop_grid GridDest" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Miejsca (należące do wycieczki)</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNazwa" runat="server" Text='<%# Eval("Nazwa") %>' />
<asp:HiddenField ID="IDVal" ClientIDMode="Static" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
There is my Code-Behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
recID = int.Parse(Request.QueryString["id"]);
if (recID > 0)
{
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Nazwa", typeof(string)) });
dt2.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Nazwa", typeof(string)) });
Miejsca ms = new Miejsca();
Hashtable hs = new Hashtable();
foreach (var lst in ms.PobierzMiejscaLista(hs))
{
dt.Rows.Add(lst.Id , lst.Nazwa);
}
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
Wycieczka w = (new Wycieczki()).PobierzWycieczke(recID);
foreach (var lst in w.Miejsca)
{
Miejsce tempM = (new Miejsca()).PobierzMiejsce(lst.Id_Miejsce.Id);
dt2.Rows.Add(tempM.Id, tempM.Nazwa);
}
int ilosc = dt2.Rows.Count;
//gvDest.UseAccessibleHeader = true;
gvDest.DataSource = dt2;
gvDest.DataBind();
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "TablicaMiejsc", "loadPlacesIntoTrip("+recID+");", true);
}
}
else
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("Nazwa") });
Miejsca ms = new Miejsca();
Hashtable hs = new Hashtable();
foreach (var lst in ms.PobierzMiejscaLista(hs))
{
//listMiejsc.Add(lst);
dt.Rows.Add(lst.Id, lst.Nazwa);
}
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
gvDest.DataSource = new List<String>();
gvDest.DataBind();
recID = 0;
}
}
}
And i don't know why but only one GridView (gvSource) display data.
Second GridView (gvDest) not display data.
When i debug code i see both DataTables have data. Both GridView DataSources have data too. But only one GridView display data.
I use Nhibernate to lazy load (w.Miejsca) collection and get objects like "Miejsce" or "Wycieczka" from database. Also I use JQuery and JQuery UI to make sortable GridViews.
Sorry for my bad english, it's not my native language.
I hope you can help me :)
UPDATE
Finally I found what is responsible for this situation.
Because of my stupidity i lost a lot of time :)
This line of code is removed the items from GridView:
$("[id*=gvDest] tr:not(tr:first-child)").remove();
Thank you for your advice.
The problem was solved.

Please remove ClientIDMode="Static" from second grid view and check it.

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.

How to call a function at regular interval which accesses and updates UI controls?

The basic Idea of this web app is a chatroom and the GridView showing the chats should be refreshed by selecting latest chats from database and storing in DataTable which is the DataSource of the Gridview. The GridView's markup is as follows:-
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
Width="545px" HeaderStyle-BorderStyle="None" HeaderStyle-Height="0px">
<Columns>
<asp:TemplateField>
<HeaderStyle Height="0px" Wrap="False" />
<ItemStyle BackColor="#CCCCCC" ForeColor="Black" Width="394px"
BorderStyle="None" />
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("user") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text=": "></asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("chat") %>'></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text='<%# Bind("date") %>' Font-Size="Small" ForeColor="Gray"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BorderStyle="None" Height="0px" />
</asp:GridView>
There's of course another GridView containing users names. When one of them is clicked the RowCommand event is fired:-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowValue = Convert.ToInt32(e.CommandArgument.ToString());
GridView1.SelectedIndex = rowValue;
show_chats();
}
And Finally, here's the show_chats function:-
public void show_chats()
{
if (GridView1.SelectedIndex >= 0)
{
LinkButton ul = (LinkButton)GridView1.Rows[GridView1.SelectedIndex].FindControl("userList");
string gridViewValue = ul.Text;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from chats where (chatFrom='" + user + "' and chatTo='" + gridViewValue + "') OR (chatFrom='" + gridViewValue + "' and chatTo='" + user + "') order by dateTime", conn);
conn.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 0)
{
txtChat.Text = "No past chats, Type here to get started";
chats.Clear();
GridView2.DataSource = chats;
GridView2.DataBind();
}
else
{
chats.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = chats.NewRow();
row[0] = dt.Rows[i][0].ToString();
row[1] = dt.Rows[i][2].ToString();
row[2] = dt.Rows[i][3].ToString();
chats.Rows.Add(row);
}
GridView2.DataSource = chats;
GridView2.DataBind();
txtChat.Text = "";
}
}
}
Now I want the show_chats function to be called at regular interval to check for new messages whenever an user is selected from GridView1 (which contains the user names).
I tried using thread but I guess I'm doing it wrong, because it is throwing exceptions which are not thrown when I am not using thread.
If I have to use threading please tell me how to use it properly.
Use 'Threading.Thread' for independent execution of a function and Threading.Timer to call that function on interval.
Declaring Threading.Timer :
System.Threading.Timer TimerForXYZ = new System.Threading.Timer(TickForXYZ, null, 0, 1000); // this will call method TickForXYZ after every 1 second
Declaring Threading.Thread :
private void TickForXYZ(object obj)
{
Thread myThreadXYZ = new Thread(new System.Threading.ThreadStart(XYZ));
myThreadXYZ .IsBackground = true;
myThreadXYZ .Start();
}
Your Method to run periodically :
private void XYZ()
{
// Your code goes here
// This function will run after every 1s
}
Alternately you can use timers in javascript to call a ajax function, which will load your grid.
Let me know if you need any help with this.

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'.

how to get binded drop down list while users pagging and sorting in asp.net 3.5

i have grid view which have two drop down list. so user can change drop down list value at run time. here is my grid view design code :
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<HeaderTemplate>
<asp:LinkButton ID="lbut_sortstatus1" runat="server"
CommandArgument="status_id" CommandName="Sort" CssClass="normaltext"
Font-Bold="true" Text="Status"></asp:LinkButton>
<asp:PlaceHolder ID="placeholderstatus1" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDL_StatusList1" runat="server"
DataTextField="status_name" DataValueField="Id" AppendDataBoundItems="true"
AutoPostBack="True"
onselectedindexchanged="DDL_StatusList1_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="DDL_StatusList1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
<HeaderStyle CssClass="headinglist_bg" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
how ever this is my Page_Load code :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Status();
Bind_DDL_Group();
Bind_DDL_Countries();
}
this.GetData();
}
and here is my one of drop down list bind method that shows how i binding grid view drop down list.
public void Bind_DDL_Group()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Groups.Select(g=>g).OrderBy(g=>g.Group_name).ToList();
DataSet myDataset = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Group_name", typeof(string));
foreach (var item in query)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Group_name"] = item.Group_name.ToString();
dt.Rows.Add(dr);
}
myDataset.Tables.Add(dt);
DDL_GroupList.DataSource = myDataset;
DDL_GroupList.DataBind();
DropDownList bind_dropdownlist;
foreach (GridViewRow grdRow in GV_ViewUserList.Rows)
{
bind_dropdownlist = (DropDownList)(GV_ViewUserList.Rows[grdRow.RowIndex].Cells[8].FindControl("DDL_GroupList1"));
bind_dropdownlist.DataSource = myDataset;
bind_dropdownlist.DataBind();
}
}
}
however at Page load first time it's works successfully but when user clicks sorting or pagging then drop down list get empty. how ever i binds them in (!Page.IsPostBack) of Page_Load.
what I'm doing wrong here..
please help me...
Please put dropdown binding code out of if(!Page.IsPostBack) condition
Because when go to another page in gridview Page will be posted back to server
and if(!Page.IsPostBack) condition will return false.
Change your code to
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Countries();
}
Bind_DDL_Status();
Bind_DDL_Group();
this.GetData();

asp.net and c# problems saving new data from new row added to a gridview

I am having a problem with gridviews. Basically I am writing an aircraft information and tracking system and in the process getting to know the wonders of gridviews, but I have trouble with adding a new row to the gridview. I am able to create a new row to input the data when a button is pressed, but when I click on update, I am having some sort of postback problem that is causing that data to be forgotten and can't find a way around it. The datasource is a list of cargodoor objects that contain doubles and strings holding measurements, names etc. Here is my code.
<asp:UpdatePanel ChildrenAsTriggers="true" ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="divAddCargoDoor" style="width:100%" runat="server" class="AlignRight">
<asp:LinkButton ID="lbAddNewCargoDoor" runat="server"
Text="<%$ Resources:ls, AddCargoDoor %>"
OnClick="lbAddNewCargoDoor_Click"></asp:LinkButton><br /><br />
</div>
<div id="divCargoDoorNoDoors" runat="server">
<asp:Label ID="lCargoDoorNoDoors" runat="server"
Text="<%$ Resources:ls, NoCargoDoors %>"></asp:Label>
</div>
<asp:GridView ID="gvCargoDoors" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" Width="100%"
OnRowEditing="gvCargoDoors_RowEditing"
OnRowUpdating="gvCargoDoors_RowUpdating"
OnRowDeleting="gvCargoDoors_RowDeleting"
OnRowCancelingEdit="gvCargoDoors_RowCancellingEdit">
<Columns>
<asp:CommandField AccessibleHeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField AccessibleHeaderText="Name"
HeaderText="<%$ Resources:ls, Description %>">
<ItemTemplate>
<asp:Label ID="lName" runat="server" Text='<%# Bind("Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Name" runat="server" Text='<%# Bind("Name") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Width"
HeaderText="<%$ Resources:ls, Width %>">
<ItemTemplate>
<asp:Label ID="lWidth" runat="server" Text='<%# Bind("Width") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CDWidth" runat="server" Text='<%# Bind("Width") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Height"
HeaderText="<%$ Resources:ls, Height %>">
<ItemTemplate>
<asp:Label ID="lHeight" runat="server" Text='<%# Bind("Height") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CDHeight" runat="server" Text='<%# Bind("Height") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField AccessibleHeaderText="Delete" ShowDeleteButton="True"
DeleteText="X" />
</Columns>
</asp:GridView>
<br />
</ContentTemplate>
</asp:UpdatePanel>
Now for the C# code
First we have this piece that gets the information from the database that is used to build the datasource. It calls a simple sql database call to the SQL Server 2008 database and returns the data in an aircraft object, that contains a list of cargodoor objects.
private void BuildDataSource()
{
this.ac = Charter.Aircraft.Retrieve(Convert.ToInt32(this.hfAircraftID.Value));
}
Now here is the code for the actual cargo door controls
private void BindCargoDoors()
{
if (ac.CargoDoors.Count == 0)
{
//display a label telling user there are no cargo doors
divCargoDoorNoDoors.Visible = true;
}
else
{
//bind the cargodoor object list to the gridview
divCargoDoorNoDoors.Visible = false;
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
this.gvCargoDoors.DataBind();
}
}
protected void gvCargoDoors_RowEditing(object sender, GridViewEditEventArgs e)
{
//get the index of the row and enter row editing mode
this.gvCargoDoors.EditIndex = e.NewEditIndex;
BuildDataSource();
BindCargoDoors();
}
protected void gvCargoDoors_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//get the row being edited
GridViewRow row = this.gvCargoDoors.Rows[e.RowIndex];
//create a new cargo door to store the info in
CargoDoor cd = new CargoDoor();
//Retrieve the id of the cargodoor
cd.Id = Convert.ToInt32(gvCargoDoors.DataKeys[e.RowIndex].Values["Id"]);
if (cd.Id == 0) //will apply when new cargodoor is added
{
//fill in the cargodoor object from data in the row
cd.DateAdded = DateTime.Now;
cd.DateModified = DateTime.Now;
cd.Name = ((TextBox)row.FindControl("Name")).Text;
cd.Width = Convert.ToDouble(((TextBox)row.FindControl("Width")).Text);
cd.Height = Convert.ToDouble(((TextBox)row.FindControl("Height")).Text);
cd.Owner = this.ac.Owner;
cd.AircraftId = this.ac.Id;
//insert the new cargodoor into the database
Charter.Aircraft.InsertCargoDoor(cd);
}
else
{
//Retrieve old cargodoor info and fill in object info into cd
CargoDoor cdOrig = Charter.Aircraft.RetrieveCargoDoorByID(cd.Id);
//fill in the cargodoor object with retrieved info
cd.AircraftId = cdOrig.AircraftId;
cd.DateAdded = cdOrig.DateAdded;
cd.Notes = cdOrig.Notes;
cd.Owner = cdOrig.Owner;
//fill in updated information
cd.Name = ((TextBox)row.FindControl("Name")).Text;
cd.Width = Convert.ToInt32(((TextBox)row.FindControl("Width")).Text);
cd.Height = Convert.ToInt32(((TextBox)row.FindControl("Height")).Text);
cd.DateModified = DateTime.Now;
//save the new cargodoor info
Charter.Aircraft.UpdateCargoDoor(cd);
}
//rebuild data source to get new cargo door
BuildDataSource();
//Reset the edit index.
this.gvCargoDoors.EditIndex = -1;
//Bind data to the GridView control.
BindCargoDoors();
}
protected void gvCargoDoors_RowCancellingEdit(object sender,
GridViewCancelEditEventArgs e)
{
this.gvCargoDoors.EditIndex = -1;
BuildDataSource();
BindCargoDoors();
}
protected void gvCargoDoors_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
BuildDataSource();
int id = Convert.ToInt32(gvCargoDoors.DataKeys[e.RowIndex].Values["Id"]);
Charter.Aircraft.DeleteCargoDoor(id);
BuildDataSource();
BindCargoDoors();
}
protected void lbAddNewCargoDoor_Click(object sender, EventArgs e)
{
//trigger the edit mode with an edit row index of 0
this.gvCargoDoors.SetEditRow(0);
//insert a new cargodoor into the source object
this.ac.CargoDoors.Insert(0, new CargoDoor());
//bind the data
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
BindCargoDoors();
}
My big problem is to do with the lbAddNewCargoDoor and the editing of a row. When the update link is pressed it has forgotten that a new row was added and so just edits the row that already exists, rather than inserting a new cargodoor object into the database. I am just not sure on the order of operations to prevent this from screwing up.
Any help would be appreciated. Thanks.
try changing (see the change in order of statements)
protected void lbAddNewCargoDoor_Click(object sender, EventArgs e)
{
//trigger the edit mode with an edit row index of 0
this.gvCargoDoors.SetEditRow(0);
//insert a new cargodoor into the source object
this.ac.CargoDoors.Insert(0, new CargoDoor());
//bind the data
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
BindCargoDoors();
}
to
protected void lbAddNewCargoDoor_Click(object sender, EventArgs e)
{
//insert a new cargodoor into the source object
this.ac.CargoDoors.Insert(0, new CargoDoor());
//bind the data
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
//trigger the edit mode with an edit row index of 0
this.gvCargoDoors.SetEditRow(0);
BindCargoDoors();
}
Please note that I cannot add comments (due to less reputation) and I am aware that this should be a comment.

Categories