adding textbox in dataTable - asp.net

I want to add textBox in my dataTable.My dataTable is dynamically created and bind to gridView.When I try to add new row on button click gives me this error:
Index was out of range. Must be non-negative and less than the size of
the collection.
Parameter name: index
TextBox TextBox1 = (TextBox)GridView2.Rows[0].Cells[2].FindControl("TextBox1");
Here is my code:
Markup:
<asp:GridView ID="GridView2" runat="server"
ShowHeader="true"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CssClass="button2"
OnClick="btnTest_Click"
Text="-"
Width="100px"
Font-Bold="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TextBox1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
private void AddNewRecordRowToGridf()
{
//creating DataTable
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "Markici";
//creating columns for DataTable
dt.Columns.Add(new DataColumn("FirmaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Godina", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("KasaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("MarkicaID", typeof(System.Int64)));
dt.Columns.Add(new DataColumn("Datum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Masa", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VrabotenID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Artikal", typeof(System.String)));
dt.Columns.Add(new DataColumn("Cena1", typeof(System.String)));
dt.Columns.Add(new DataColumn("Kolicina", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("Smena", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VkIznos", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("VkDanok", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("SysDatum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Vid", typeof(System.String)));
dt.Columns.Add(new DataColumn("EdMera", typeof(System.String)));
dt.Columns.Add(new DataColumn("ArtikalID", typeof(System.String)));
dt.Columns.Add(new DataColumn("TarifaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Zabeleshka", typeof(System.String)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["Markici2"] = dt;
if (ViewState["Markici2"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici2"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBox1 = (TextBox)GridView2.Rows[0].Cells[2].FindControl("TextBox1");
//Creating new row and assigning values
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label12.Text;
drCurrentRow["Cena1"] = Label13.Text;
if (Session["MinusVrganj"] != null)
{
drCurrentRow["Kolicina"] = Convert.ToInt32(Session["MinusVrganj"]) + Counter; //Label5.Text; //count;
}
drCurrentRow["Kolicina"] = Label11.Text; //count;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label17.Text;//Counter1 * Convert.ToDecimal(Label13.Text); //Label17.Text;
drCurrentRow["VkDanok"] = Label18.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label24.Text;
drCurrentRow["Edmera"] = Label16.Text;
drCurrentRow["ArtikalID"] = Label34.Text;
drCurrentRow["TarifaID"] = Label14.Text;
drCurrentRow["Zabeleshka"] = TextBox1.Text;
}
dtCurrentTable.Rows.Add(drCurrentRow);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}

Related

How to export data with paging enabled

I'm trying to export data however it only extract the data in current paging. And I need to go to another paging to download another. Is there any where to download all data in the source?
Below is my aspx code:
<asp:datagrid id="dgAmount" Visible=false runat="server" CssClass="item01Nxx08" Width="100%" CellPadding="3"
BorderColor="#DEDFDE" BorderStyle="None" PageSize="50" AutoGenerateColumns="False" AllowSorting="True"
AllowPaging="True" BackColor="White" BorderWidth="1px" GridLines="Vertical" ForeColor="Black">
<asp:BoundColumn DataField="No" SortExpression="No" HeaderText="No" visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="Action" SortExpression="Action" HeaderText="Action"></asp:BoundColumn>
<asp:BoundColumn DataField="AppName" SortExpression="AppName" HeaderText="Approver Name"></asp:BoundColumn>
<asp:BoundColumn DataField="MIAmount" SortExpression="MIAmount" HeaderText="MI Amount"></asp:BoundColumn>
<asp:BoundColumn DataField="By" SortExpression="By" HeaderText="By">
</asp:BoundColumn>
<asp:BoundColumn DataField="Date" SortExpression="Date" HeaderText="Date">
</asp:BoundColumn>
</asp:DataGrid>
And below is my vb code:
System.Web.HttpContext.Current.Response.Clear()
System.Web.HttpContext.Current.Response.Buffer = True
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=" & fileName & ".xls;")
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
System.Web.HttpContext.Current.Response.Charset = ""
'set the response mime type for excel
'create a string writer
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
'create an htmltextwriter which uses the stringwriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
htmlWrite.WriteLine("<b><u>" & header & "</u></b><br /><br />")
'instantiate a datagrid
Dim dg As New DataGrid()
Dim dt As New DataTable, dr As DataRow
dt.Columns.Add(New DataColumn("No", GetType(Integer)))
dt.Columns.Add(New DataColumn("Action", GetType(String)))
dt.Columns.Add(New DataColumn("Approver Name", GetType(String)))
dt.Columns.Add(New DataColumn("MI Amount", GetType(String)))
dt.Columns.Add(New DataColumn("By", GetType(String)))
dt.Columns.Add(New DataColumn("Date", GetType(String)))
Dim tempDg As DataGrid = dgAmount
For Each item As DataGridItem In tempDg.Items
dr = dt.NewRow()
dr("No") = item.Cells(0).Text
dr("Action") = item.Cells(1).Text
dr("Approver Name") = item.Cells(2).Text
dr("MI Amount") = item.Cells(3).Text
dr("By") = item.Cells(4).Text
dr("Date") = item.Cells(5).Text
dt.Rows.Add(dr)
Next
dg.DataSource = dt
dg.DataBind()
dg.EnableViewState = False
dg.GridLines = GridLines.None
dg.HeaderStyle.Font.Name = "Verdana"
dg.HeaderStyle.Font.Size = 8
dg.HeaderStyle.Font.Bold = True
dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
dg.HeaderStyle.ForeColor = Drawing.Color.White
dg.HeaderStyle.BackColor = Drawing.Color.Black
dg.ItemStyle.Font.Name = "Verdana"
dg.ItemStyle.Font.Size = 8
dg.ItemStyle.VerticalAlign = VerticalAlign.Top
'bind the modified datagrid
'tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite)
'output the html
System.Web.HttpContext.Current.Response.Write(stringWrite.ToString)
System.Web.HttpContext.Current.Response.End()
System.Web.HttpContext.Current.Response.Redirect("")
Turn Paging off before bind/export. grid.AllowPaging = false;

User should only be able to select 1 item in a list only once

I have a gridview where I'm allowing user to select items for billing. now my problem is that the user is able to select same item twice in only one bill.
screen for reference:
Here the user is able to select duplicate items in the list which is not good.
my ASPX Markup:
<asp:GridView ID="Gridview1" runat="server" CssClass="table table-bordered table-hover table-responsive" ShowFooter="True" AutoGenerateColumns="False" OnRowDataBound="gvRowDataBound" OnRowDeleting="Gridview1_RowDeleting1" EmptyDataText="Data Not Available">
<Columns>
<asp:CommandField ShowDeleteButton="true" ControlStyle-CssClass="btn btn-danger fa fa-trash" DeleteText="" HeaderText="Remove Items" />
<asp:BoundField DataField="RowNumber" HeaderText="Sl. No." />
<asp:TemplateField HeaderText="Item Name" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:DropDownList ID="drpItemname" runat="server" Width="200px" CssClass="form-control select2" OnSelectedIndexChanged="GetItemDetails" AutoPostBack="true"></asp:DropDownList>
</ItemTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="HSN Code" Visible="false" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txthsn" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Available Quantity" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtQttyAvailable" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtQtty" runat="server" CssClass="form-control" OnTextChanged="CalculateTotal" AutoPostBack="true" Enabled="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtUnitPrice" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discount" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtdisc" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtsgst" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtcgst" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="I.GST" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtigst" runat="server" AutoPostBack="true" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price" ConvertEmptyStringToNull="False" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtTotalPrice" runat="server" CssClass="form-control" Enabled="False"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="AddItem" CausesValidation="False" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My c# code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Mylogic();
SetInitialRow();
ce1.StartDate = DateTime.Now.AddDays(-60);
ce1.SelectedDate = DateTime.Now.Date;
BindGrid();
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dt.Columns.Add(new DataColumn("Column7", typeof(string)));
dt.Columns.Add(new DataColumn("Column8", typeof(string)));
dt.Columns.Add(new DataColumn("Column9", typeof(string)));
dt.Columns.Add(new DataColumn("Column10", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dr["Column7"] = string.Empty;
dr["Column8"] = string.Empty;
dr["Column9"] = string.Empty;
dr["Column10"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void GetItemDetails(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox QttyAvailable = row.FindControl("txtQttyAvailable") as TextBox;
TextBox UnitPrice = row.FindControl("txtUnitPrice") as TextBox;
TextBox HsnCode = row.FindControl("txthsn") as TextBox;
TextBox Discount = row.FindControl("txtdisc") as TextBox;
TextBox SGST = row.FindControl("txtsgst") as TextBox;
TextBox CGST = row.FindControl("txtcgst") as TextBox;
TextBox IGST = row.FindControl("txtigst") as TextBox;
SqlConnection conn = new SqlConnection(constring);
conn.Open();
string str = "select * from Stock where itemname='" + ddl1.SelectedItem.ToString() + "'";
SqlCommand com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
UnitPrice.Text = reader["unitprice"].ToString();
QttyAvailable.Text = reader["qtty"].ToString();
HsnCode.Text = reader["hsn"].ToString();
Discount.Text = reader["disc"].ToString();
SGST.Text = reader["sgst"].ToString();
CGST.Text = reader["cgst"].ToString();
IGST.Text = reader["igst"].ToString();
}
reader.Close();
conn.Close();
}
}
}
}
protected void CalculateTotal(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
foreach (GridViewRow row in Gridview1.Rows)
{
TextBox lblQty = row.FindControl("txtQttyAvailable") as TextBox;
TextBox lblReceiveQty = row.FindControl("txtQtty") as TextBox;
if (lblQty != null && lblReceiveQty != null)
{
int Qty = 0, ReceiveQty = 0;
if (!string.IsNullOrEmpty(lblQty.Text))
{
Qty = int.Parse(lblQty.Text);
}
if (!string.IsNullOrEmpty(lblReceiveQty.Text))
{
ReceiveQty = int.Parse(lblReceiveQty.Text);
}
if (ReceiveQty > Qty)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Required quantity can not ne greater than available stock!', 'Royal Riders, Vijayapura', 'warning');", true);
lblReceiveQty.Text = "";
lblReceiveQty.Focus();
}
else if (Qty >= ReceiveQty)
{
TextBox AQtty = row.FindControl("txtQttyAvailable") as TextBox;
TextBox QttyReq = row.FindControl("txtQtty") as TextBox;
TextBox UnitPrice = row.FindControl("txtUnitPrice") as TextBox;
TextBox TotPrice = row.FindControl("txtTotalPrice") as TextBox;
TextBox DiscountPrice = row.FindControl("txtdisc") as TextBox;
DropDownList ItemName = row.FindControl("drpItemname") as DropDownList;
Control ctrl = row.FindControl("txtQtty") as TextBox;
if (ctrl != null)
{
TextBox txt1 = (TextBox)ctrl;
if (txt.ClientID == txt1.ClientID)
{
decimal totamt = Convert.ToDecimal(QttyReq.Text) * Convert.ToDecimal(UnitPrice.Text);
decimal discountrate = (totamt) - (totamt * Convert.ToDecimal(DiscountPrice.Text)) / 100;
TotPrice.Text = discountrate.ToString("#,0.00");
}
}
}
}
}
}
public static decimal totalgst;
public static decimal totalnetamt;
public static Int32 InitialStock;
protected void gvRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpItemName = (e.Row.FindControl("drpItemName") as DropDownList);
foreach (GridViewRow row2 in Gridview1.Rows)
{
TextBox txt = row2.FindControl("txtTotalPrice") as TextBox;
txt.Text = "0";
}
drpItemName.DataSource = GetData("SELECT itemname FROM Stock where rem != '1'");
drpItemName.DataTextField = "itemname";
drpItemName.DataValueField = "itemname";
drpItemName.DataBind();
drpItemName.Items.Insert(0, new ListItem("Please select"));
}
}
private DataSet GetData(string query)
{
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("drpItemName");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txthsn");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtQttyAvailable");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtQtty");
TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txtUnitPrice");
TextBox box6 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("txtdisc");
TextBox box7 = (TextBox)Gridview1.Rows[rowIndex].Cells[7].FindControl("txtsgst");
TextBox box8 = (TextBox)Gridview1.Rows[rowIndex].Cells[8].FindControl("txtcgst");
TextBox box9 = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtigst");
TextBox box10 = (TextBox)Gridview1.Rows[rowIndex].Cells[10].FindControl("txtTotalPrice");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = box6.Text;
dtCurrentTable.Rows[i - 1]["Column7"] = box7.Text;
dtCurrentTable.Rows[i - 1]["Column8"] = box8.Text;
dtCurrentTable.Rows[i - 1]["Column9"] = box9.Text;
dtCurrentTable.Rows[i - 1]["Column10"] = box10.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList box1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("drpItemName");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txthsn");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtQttyAvailable");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtQtty");
TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txtUnitPrice");
TextBox box6 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("txtdisc");
TextBox box7 = (TextBox)Gridview1.Rows[rowIndex].Cells[7].FindControl("txtsgst");
TextBox box8 = (TextBox)Gridview1.Rows[rowIndex].Cells[8].FindControl("txtcgst");
TextBox box9 = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtigst");
TextBox box10 = (TextBox)Gridview1.Rows[rowIndex].Cells[10].FindControl("txtTotalPrice");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
box5.Text = dt.Rows[i]["Column5"].ToString();
box6.Text = dt.Rows[i]["Column6"].ToString();
box7.Text = dt.Rows[i]["Column7"].ToString();
box8.Text = dt.Rows[i]["Column8"].ToString();
box9.Text = dt.Rows[i]["Column9"].ToString();
box10.Text = dt.Rows[i]["Column10"].ToString();
rowIndex++;
if (!string.IsNullOrEmpty(box10.Text) && !string.IsNullOrEmpty(box10.Text))
{
box10.Text = dt.Rows[i]["Column10"].ToString();
}
else
{
box10.Text = "0";
}
}
}
}
}
protected void Confirm(object sender, EventArgs e)
{
decimal sum = 0;
decimal grandgst = 0;
try
{
foreach (GridViewRow g12 in Gridview1.Rows)
{
Control ctrl2 = g12.FindControl("txtigst") as TextBox;
if (ctrl2 != null)
{
TextBox txt1 = (TextBox)ctrl2;
TextBox cgst = g12.FindControl("txtcgst") as TextBox;
TextBox sgst = g12.FindControl("txtsgst") as TextBox;
TextBox igst = g12.FindControl("txtigst") as TextBox;
TextBox linegst = g12.FindControl("txtTotalPrice") as TextBox;
TextBox totamt = g12.FindControl("txtTotalPrice") as TextBox;
sum += decimal.Parse(((TextBox)(g12.Cells[10].FindControl("txtTotalPrice"))).Text);
decimal fcgst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(cgst.Text) / 100;
decimal fsgst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(sgst.Text) / 100;
decimal figst = Convert.ToDecimal(totamt.Text) * Convert.ToDecimal(igst.Text) / 100;
decimal ftot = Convert.ToDecimal(totamt.Text);
totalgst = fcgst + fsgst + figst;
grandgst += totalgst;
totalnetamt = grandgst + sum;
}
}
lblGstTotal.Text = grandgst.ToString();
lblGTotal.Text = sum.ToString();
lblGrandTotal.Text = (sum + grandgst).ToString();
foreach (GridViewRow g1 in Gridview1.Rows)
{
string ITEMNAME = (g1.FindControl("drpItemname") as DropDownList).Text;
string HSN = (g1.FindControl("txthsn") as TextBox).Text;
string QTY = (g1.FindControl("txtQtty") as TextBox).Text;
string UP = (g1.FindControl("txtUnitPrice") as TextBox).Text;
string DIS = (g1.FindControl("txtdisc") as TextBox).Text;
string SGST = (g1.FindControl("txtsgst") as TextBox).Text;
string CGST = (g1.FindControl("txtcgst") as TextBox).Text;
string IGST = (g1.FindControl("txtigst") as TextBox).Text;
string TOT = (g1.FindControl("txtTotalPrice") as TextBox).Text;
string InsertQuery = "Insert into Sales(bno,cdate,ctime,name,mobileno,address,gstno,pan,description,hsn,qtty,rate,disc,sgst,cgst,igst,linetotal,netamt,totalgst,grsamt,status,rem) values(#bno,#cdate,#ctime, #name, #mobileno, #address, #gstno, #pan, #description, #hsn, #qtty, #rate, #disc, #sgst, #cgst,#igst,#linetotal,#netamt,#totalgst,#grsamt,'1','0')";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(InsertQuery, con))
{
cmd.Parameters.AddWithValue("#bno", Convert.ToInt64(lblBillNo.Text));
cmd.Parameters.AddWithValue("#cdate", txtBDate.Text.ToString());
cmd.Parameters.AddWithValue("#ctime", systemtime.ToString());
cmd.Parameters.AddWithValue("#name", txtcname.Text);
cmd.Parameters.AddWithValue("#mobileno", txtcmobile.Text);
cmd.Parameters.AddWithValue("#address", txtcaddress.Text);
cmd.Parameters.AddWithValue("#gstno", txtgst.Text);
cmd.Parameters.AddWithValue("#pan", txtcpan.Text);
cmd.Parameters.AddWithValue("#description", ITEMNAME);
cmd.Parameters.AddWithValue("#hsn", HSN);
cmd.Parameters.AddWithValue("#qtty", QTY);
cmd.Parameters.AddWithValue("#rate", Convert.ToDecimal(UP));
cmd.Parameters.AddWithValue("#disc", Convert.ToDecimal(DIS));
cmd.Parameters.AddWithValue("#sgst", Convert.ToDecimal(SGST));
cmd.Parameters.AddWithValue("#cgst", Convert.ToDecimal(CGST));
cmd.Parameters.AddWithValue("#igst", Convert.ToDecimal(IGST));
cmd.Parameters.AddWithValue("#linetotal", Convert.ToDecimal(TOT));
cmd.Parameters.AddWithValue("#grsamt", (lblGTotal.Text));
cmd.Parameters.AddWithValue("#totalgst", Convert.ToDecimal(lblGstTotal.Text));
cmd.Parameters.AddWithValue("#netamt", Convert.ToDecimal(lblGrandTotal.Text));
int i = cmd.ExecuteNonQuery();
if(i > 0)
{
DropDownList ItemName = g1.FindControl("drpItemname") as DropDownList;
TextBox ReqQtty = g1.FindControl("txtQtty") as TextBox;
using (SqlConnection DeductStockCon = new SqlConnection(constring))
{
string query = "update Stock set qtty=CAST(IsNULL(qtty, '0') as int) - '" + Convert.ToInt32(ReqQtty.Text) + "' where itemname='" + ItemName.SelectedItem.ToString() + "'";
DeductStockCon.Open();
using (SqlCommand DeductStockCmd = new SqlCommand(query, DeductStockCon))
{
int j = DeductStockCmd.ExecuteNonQuery();
if (j > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Items inserted successfully!', 'Royal Riders, Vijayapura', 'success');", true);
}
}
}
}
}
}
}
LoadReceipt();
Clear();
Mylogic();
SetInitialRow();
}
catch (Exception ex)
{
throw ex;
}
}
private void Clear()
{
txtcname.Text = "";
txtcmobile.Text = "";
txtcaddress.Text = "";
txtcpan.Text = "";
txtgst.Text = "";
drpMode.SelectedValue = "--Select Payment Mode--";
}
private void Mylogic()
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT MAX(bno) + 1 as Billno FROM Sales", con))
lblBillNo.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
}
protected void AddItem(object sender, EventArgs e)
{
try
{
AddNewRowToGrid();
decimal sum = 0;
foreach (GridViewRow row1 in Gridview1.Rows)
{
TextBox val1 = row1.FindControl("txtTotalPrice") as TextBox;
if (!string.IsNullOrEmpty(val1.Text) && !string.IsNullOrEmpty(val1.Text))
{
sum += 0;
}
else
{
sum += decimal.Parse(((TextBox)(row1.Cells[10].FindControl("txtTotalPrice"))).Text);
}
}
lblGTotal.Text = sum.ToString();
}
catch (Exception ex)
{
lblGTotal.Text = ex.Message.ToString();
}
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
SetInitialRow();
BindGrid();
}
protected void BindGrid()
{
Gridview1.DataSource = ViewState["CurrentTable"] as DataTable;
Gridview1.DataBind();
}
private void LoadReceipt()
{
SqlConnection CN;
string MyConnectionString = null;
MyConnectionString = constring;
CN = new SqlConnection(MyConnectionString);
CN.Open();
string SQL = null;
SQL = "SELECT * FROM Sales where bno=(select max(bno) as 'Billno' from Sales)";
SqlDataAdapter myDA = new SqlDataAdapter(SQL, CN);
CN.Close();
SalesDataset DS = new SalesDataset();
myDA.Fill(DS, "Sales");
ReportDocument myRPT = new ReportDocument();
myRPT.Load(Server.MapPath("Reports/BillReciept.rpt"));
myRPT.SetDataSource(DS);
rptSales.ReportSource = myRPT;
rptSales.SeparatePages = false;
}
protected void btnLastReport_Click(object sender, EventArgs e)
{
LoadReceipt();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
SetPreviousData();
}
private void ResetRowID(DataTable dt)
{
int rowNumber = 1;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
row[0] = rowNumber;
rowNumber++;
}
}
}
protected void Gridview1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
dt.Rows.RemoveAt(e.RowIndex);
Gridview1.DataSource = dt;
Gridview1.DataBind();
SetPreviousData();
if(Gridview1.Rows.Count <= 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('This is the only item in the list!', 'Royal Riders, Vijayapura', 'success');", true);
SetInitialRow();
}
}
You can do it in two ways
Handle the code in GetItemDetails() Event Method do a foreach and check if the name selected in the drpItemname dropdown eqauls with the name of any of the previous drpItemname dropdownlist of the gridview
In the Method AddNewRowToGrid() before binding data to drpItemname dropdown remove those values from the list which are already selected in the previous drpItemname dropdown and then bind it and add row [Note this will work ambiguos because if user changes the dropdownvalue of previous list then you will get problem ]
Are these ideas helpfull ?
Ex 1 -
protected void GetItemDetails(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if((ddl1.ClientId != ddl.ClientId) && (ddl1.SelectedIndex == ddl.SelectedIndex)){
return Response.Write("Error") //
}
}
}
}

add rows in dataTable from different buttons asp.net]

Hello i have problem with data Table. I want to insert new row in data Table every time when user click on button.I have 10 buttons and when user click on button 1,it insert new row but when user clicks on button 2 existing row is replaced with new one. HELP!
////here i call methods for adding new rows from button clicks
private void RemoveDuplicates (Data_Table dt)
{
if (ViewState["Markici"] != null)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = dtCurrentTable.Rows.Count - 1; i >= 0; i--)
{
if (i == 0)
{
break;
}
for (int j = i - 1; j >= 0; j--)
{
if (dtCurrentTable.Rows[i]["Cena1"].ToString() == dtCurrentTable.Rows[j]["Cena1"].ToString())
{
dtCurrentTable.Rows[i].Delete();
break;
}
}
}
}
dtCurrentTable.AcceptChanges();
// ViewState["Markici"] = dtCurrentTable;
// Repeater1.DataSource = dtCurrentTable;
// Repeater1.DataBind();
AddNewRecordRowToGrid();
AddNewRecordRowToGridf();
decimal vkupno = 0m;
vkupno += Convert.ToDecimal(Label6.Text);
decimal vkupno2 = 0m;
vkupno2 += Convert.ToDecimal(Label17.Text);
vkupno += vkupno2;
Label26.Text = vkupno.ToString();
//xml table
// DataSet ds = new DataSet();
// ds.Tables.Add(dtCurrentTable);
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
//method for adding row, call this in button click 9
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = counter;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
drCurrentRow["Kolicina"] = Label5.Text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
/*
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
if (dtCurrentTable.Rows[i].IsNull(0) == true)
{
dtCurrentTable.Rows[i].Delete();
dtCurrentTable.AcceptChanges();
}
}*/
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
// call this in button 10 click
private void AddNewRecordRowToGridf()
{
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//Creating new row and assigning values
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label12.Text;
drCurrentRow["Cena1"] = Label13.Text;
drCurrentRow["Kolicina"] = Label11.Text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label17.Text;
drCurrentRow["VkDanok"] = Label18.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label24.Text;
drCurrentRow["Edmera"] = Label16.Text;
drCurrentRow["ArtikalID"] = Label34.Text;
}
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
if (dtCurrentTable.Rows[i].IsNull(0) == true)
{
dtCurrentTable.Rows[i].Delete();
dtCurrentTable.AcceptChanges();
}
}
/*
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.Rows[1].Delete();
dtCurrentTable.AcceptChanges();
}
*/
//Added New Record to the DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
protected void Button9_Click(object sender, EventArgs e)
{
RemoveDuplicates(dt);
}
protected void Button10_Click(object sender, EventArgs e)
{
RemoveDuplicates(dt);
}
// create DataTable
private void AddDefaultFirstRecord()
{
//creating DataTable
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "Markici";
//creating columns for DataTable
dt.Columns.Add(new DataColumn("FirmaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Godina", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("KasaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("MarkicaID", typeof(System.Int64)));
dt.Columns.Add(new DataColumn("Datum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Masa", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VrabotenID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Artikal", typeof(System.String)));
dt.Columns.Add(new DataColumn("Cena1", typeof(System.String)));
dt.Columns.Add(new DataColumn("Kolicina", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("Smena", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VkIznos", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("VkDanok", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("SysDatum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Vid", typeof(System.String)));
dt.Columns.Add(new DataColumn("EdMera", typeof(System.String)));
dt.Columns.Add(new DataColumn("ArtikalID", typeof(System.String)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["Markici"] = dt;
GridView2.DataSource = dt;
GridView2.DataBind();
}
Add dtCurrentTable.AcceptChanges(); after dtCurrentTable.Rows.Add(drCurrentRow);
Don't keep a DataTable in to ViewState. DataTable is a big object. It will affect page performance. You can keep in to cache or session.
My recomandation is to cache the datatable datasource not the datatable object.

how to add row in temporary table data table in asp.net

protected void Add_New_Click(object sender, System.EventArgs e)
{
DataTable dt= new DataTable();
DataRow dr;
dr = dt.NewRow();
string CustomerID = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
string CustomerName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerName")).Text;
string CustomerFatherName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerFatherName")).Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["sajjad_Viewstate"] = dt;
}
Try this:
protected void Add_New_Click(object sender, System.EventArgs e)
{
DataTable dt= new DataTable();
// Add columns here
dt.Columns.Add(new DataColumn("CustomerID"));
dt.Columns.Add(new DataColumn("CustomerName"));
dt.Columns.Add(new DataColumn("CustomerFatherName"));
//Create new row
DataRow dr= dt.NewRow();
string CustomerID = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
string CustomerName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerName")).Text;
string CustomerFatherName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerFatherName")).Text;
//populate columns with data
dr["CustomerID"] = CustomerID;
dr["CustomerID"] = CustomerName;
dr["CustomerFatherName"] = CustomerFatherName;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["sajjad_Viewstate"] = dt;
}
dt.Columns.Add("ItemName", typeof(string));
dt.Columns.Add("ItemCode", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Columns.Add("Qty", typeof(decimal));
dt.Columns.Add("Amount", typeof(decimal));
dr = dt.NewRow();
dr[0] = txtitemname.Text;
dr[1] = txtitemcode.Text;
dr[2] = Convert.ToDecimal(txtprice.Text);
dr[3] = Convert.ToDecimal(txtqty.Text);
dr[4] = Convert.ToDecimal(txtamount.Text);
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["DtItem"] = dt;
}
else
{
dt = (DataTable)ViewState["DtItem"];
dr = dt.NewRow();
dr[0] = txtitemname.Text;
dr[1] = txtitemcode.Text;
dr[2] = Convert.ToDecimal(txtprice.Text);
dr[3] = Convert.ToDecimal(txtqty.Text);
dr[4] = Convert.ToDecimal(txtamount.Text);
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["DtItem"] = dt;
}
grditem.DataSource =(DataTable)ViewState["DtItem"];

why pie chart is showing value for only one field?

I am trying to use a pie chart and I expect 2 regions get displayed on it. But for my following code, only the last one is shown.
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("status");
dt.Columns.Add("count");
DataRow dr = dt.NewRow();
dr["status"] = "safe";
dr["count"] = loadChart("safe");
dt.Rows.Add(dr);
dr["status"] = "unsafe";
dr["count"] = loadChart("unsafe");
dr = dt.NewRow();
dt.Rows.Add(dr);
Chart1.DataSource = dt;
Chart1.Series[0].XValueMember = "status";
Chart1.Series[0].YValueMembers = "count";
Chart1.DataBind();
}
Mark up:
<asp:Chart ID="Chart1" runat="server">
<series>
<asp:Series ChartType="Pie" Name="Series1">
</asp:Series>
</series>
<chartareas>
<asp:ChartArea Name="ChartArea1">
</asp:ChartArea>
</chartareas>
</asp:Chart>
output:
I want to see the safe portion also. I have value for it.how to resolve this issue ?
You are setting values in the same row twice:
DataRow dr = dt.NewRow();
dr["status"] = "safe";
dr["count"] = loadChart("safe");
dt.Rows.Add(dr);
//still in the same row
dr["status"] = "unsafe";
dr["count"] = loadChart("unsafe");
dr = dt.NewRow();
dt.Rows.Add(dr);
you should create new row and then set second values:
DataRow dr = dt.NewRow();
dr["status"] = "safe";
dr["count"] = loadChart("safe");
dt.Rows.Add(dr);
//new row creation
dr = dt.NewRow();
dr["status"] = "unsafe";
dr["count"] = loadChart("unsafe");
dt.Rows.Add(dr);

Resources