How to get the dropdownlistselectedid in asp.net - asp.net

var countries = context.MasterCountries.ToList();
ddlcountry.DataSource = countries;
ddlcountry.DataTextField = "Description";
ddlcountry.DataValueField = "Id";
ddlcountry.DataBind();
<asp:DropDownList runat="server" ID="ddlcountry" CssClass="textbox textbox-reg" />
int countryid = ddlcountry.SelectedIndex;
I am trying to get the id of the company but it's not working.

Try that:
int countryid = int.Parse(ddlcountry.SelectedValue);

Related

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") //
}
}
}
}

How to retain the value of selected dynamic Dropdownlist for autopostback (True)? I want to implement the cascading functionality

UI:-
<asp:GridView ID="GridView" OnPageIndexChanging="GridView1_PageIndexChanging" runat="server" AllowPaging="True" OnRowCreated="onrow_databound" ShowFooter="True" AllowSorting="True" OnSelectedIndexChanged="GridView_SelectedIndexChanged" GridLines="Both" CssClass="mydatagrid" PagerStyle-CssClass="pager"
HeaderStyle-CssClass="header" RowStyle-CssClass="rows" ForeColor="#3366FF" PageSize="4" >
<columns>
<asp:TemplateField >
<FooterTemplate>
<asp:Button ID="Button1" runat="server" Text="Insert" Height="31px" OnClick="AddButton_Click" BorderStyle="Solid" BorderColor="Black" BackColor="#6699FF" />
</FooterTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
aspx:- Binding the data and then creating dropdown at footer with on_row_bound for submission:
protected void onrow_databound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
DropDownList dr = new DropDownList();
if (i == 1)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectionConn"].ConnectionString);
List<string> values = new List<string>();
string sql = #"Select spnd_type_dsc from [dbo].[proj_spnd_type]";
using (var command = new SqlCommand(sql, con))
{
int r = 0;
con.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
values.Add(reader.GetString(r).TrimEnd(' '));
}
dr.ID = ID;
for (int j = 0; j < values.Count; j++)
{
dr.Items.Add(new ListItem(values[j]));
}
dr.AutoPostBack = false;
e.Row.Cells[i].Controls.Add(dr);
}
}
else if (i == 2)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectionConn"].ConnectionString);
string name = dr.SelectedValue;
List<string> values = new List<string>();
string sql = #"Select [prtnr_nm] from [dbo].[proj_prtnr] j inner join [dbo].[proj_spnd_type] r on j.[spnd_ty_id] =r.[spnd_type_id] where spnd_type_dsc= '" + name + "'";
using (var command = new SqlCommand(sql, con))
{
int r = 0;
con.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
values.Add(reader.GetString(r));
}
DropDownList dk = new DropDownList();
dk.ID = ID;
dk.Items.Add(new ListItem("--Select--", ""));
for (int j = 0; j < values.Count; j++)
{
dk.Items.Add(new ListItem(values[j], values[j]));
}
dk.AutoPostBack = false;
e.Row.Cells[i].Controls.Add(dk);
}
}
else if (i == 3)//Geo
{
var roleList = (List<string>)Session["Geo"];
if (roleList.Count == 1)
{
txt.Text = roleList[0].ToString();
txt.Enabled = false;
e.Row.Cells[i].Controls.Add(txt);
}
else
{
DropDownList dd = new DropDownList();
dd.ID = ID;
dd.Items.Add(new ListItem("--Select--", ""));
for (int j = 0; j < roleList.Count; j++)
{
dd.Items.Add(new ListItem(roleList[j], roleList[j]));
}
dd.AutoPostBack = false;
e.Row.Cells[i].Controls.Add(dd);
}
}
else
{
e.Row.Cells[i].Controls.Add(txt);
}
}
}
}
After putting the postback in the first dropdown. I am unable to retrieve the selected value

determine button click and modify values in another button aspx.net

I have dynamically created Data Table bind to Grid View. In every row I'm adding button which i'm define in grid view. Now I want that button to call in another button click event and make modifications in values.Is that possible?Here is my code:
<asp:GridView ID="GridView2" runat="server" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server" CommandName="odzemi" CssClass="button2" OnClick="btnTest_Click" Text="-" Width="100px" Font-Bold="True" />
<asp:Button ID="Button15" Visible="false" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
// decimal pocentDanok0 = 0.0m;
// decimal pocentDanok1 = 0.18m;
// decimal pocentDanok2 = 0.5m;
//int oldValue = int.Parse(old);
/* decimal*/ newValue = old - 1; //
Label37.Text = newValue.ToString();
decimal newIznos = oldIznos - Convert.ToDecimal(Cena1);
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
dtCurrentTable.Rows[clickedIndex].SetField("VkIznos", newIznos.ToString());
}
//I want here to call btn_test click and modyfy his values
protected void Button7_Click(object sender, EventArgs e)
{
if (GridView2.Rows.Count == 0)
{
Response.Redirect("MasiGradskaKafanak1.aspx");
}
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["string2"].ConnectionString);
Session["Counter"] = counter;
Label11.Text = counter.ToString();
// Label11.Text = Session["kolicina2"].ToString(); //ViewState["count"].ToString(); //
if (reader.Read())
{
Label35.Text = (string)reader["pkid"].ToString();
Label12.Text = (string)reader["Artikal"].ToString();
Label33.Text = (string)reader["Vid"].ToString();
Label34.Text = (string)reader["EdMera"].ToString();
Label14.Text = (string)reader["TarifaID"].ToString();
Label13.Text = (string)reader["Cena1"].ToString();
//iznos
decimal mnoz = Convert.ToDecimal(Label11.Text) * Convert.ToDecimal(Label13.Text);
Label17.Text = mnoz.ToString();
decimal.Parse(Label17.Text);
decimal cena;
cena = Convert.ToDecimal(Label13.Text);
decimal kolicina;
kolicina = Convert.ToDecimal(Label11.Text);
decimal iznos;
iznos = Convert.ToDecimal(Label17.Text);
Session["cena1"] = Label13.Text;
Session["iznos1"] = Label17.Text;
if (Label14.Text == "0")
{
decimal pocentDanok = 0.0m;
vkdanok1 = Convert.ToDecimal(vkdanok1) + Convert.ToDecimal(cena) * Convert.ToDecimal(kolicina) * Convert.ToDecimal(pocentDanok) / (1 + Convert.ToDecimal(pocentDanok));
vkdanok1 = Math.Truncate(vkdanok1 * 10000m) / 10000m;
Label18.Text = vkdanok.ToString();//vkdanok
}
else if (Label14.Text == "1")
{
decimal pocentDanok = 0.18m;
vkdanok1 = (vkdanok1) + Convert.ToDecimal(cena) * Convert.ToDecimal(kolicina) * Convert.ToDecimal(pocentDanok) / (1 + Convert.ToDecimal(pocentDanok));
vkdanok1 = Math.Truncate(vkdanok1 * 10000m) / 10000m;
Label18.Text = vkdanok1.ToString();//VkDanok
}
else if (Label14.Text == "2")
{
decimal pocentDanok = 0.5m;
vkdanok1 = Convert.ToDecimal(vkdanok1) + Convert.ToDecimal(cena) * Convert.ToDecimal(kolicina) * Convert.ToDecimal(pocentDanok) / (1 + Convert.ToDecimal(pocentDanok));
vkdanok1 = Math.Truncate(vkdanok1 * 10000m) / 10000m;
Label18.Text = vkdanok1.ToString();//vkdanok
}
conn.Close();
}
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
if (Label37.Text == "0")
{
dtCurrentTable.Rows[0]["Kolicina"] = Label11.Text;
}
else if (Label37.Text != "0")
{
Counter1 = Counter1 + 1;
dtCurrentTable.Rows[0]["Kolicina"] = Convert.ToInt32(Label37.Text) + Counter1;// Label37.Text;//Convert.ToInt32(Label37.Text) + 3;
}
dtCurrentTable.Rows[0]["Artikal"] = Label12.Text;
dtCurrentTable.Rows[0]["Cena1"] = Label13.Text;
dtCurrentTable.Rows[0]["VkIznos"] = Label17.Text;
dtCurrentTable.Rows[0]["VkDanok"] = Label18.Text;
dtCurrentTable.Rows[0]["EdMera"] = Label34.Text;
dtCurrentTable.Rows[0]["ArtikalID"] = Label35.Text;
dtCurrentTable.Rows[0]["Vid"] = Label33.Text;
dtCurrentTable.Rows[0]["TarifaID"] = Label14.Text;
dtCurrentTable.AcceptChanges();
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
RemoveDuplicates(dt);
}
You can use the EditItemTemplate to corresponding every templatefield in gridview.

Combo box with multiple columns and related values

Is it possible to show multiple columns and headers inside of a combo box/dropdown list in asp.net and show related columns values, for an example, if I click on a country name then it should show me all the cities for that country and clicking on city name should show me all the related places.
Is there any third part control available? I have checked telerik and they have combo box with multiple columns but not with related values.
I hope this will help you to get started.
<telerik:RadComboBox ID="RadComboBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged">
<ItemTemplate>
<table width="100%">
<tr>
<td>
<%# Eval("Name") %>
</td>
<td>
<%# Eval("Population")%>
</td>
</tr>
</table>
</ItemTemplate>
</telerik:RadComboBox>
<telerik:RadComboBox ID="RadComboBox2" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="RadComboBox2_SelectedIndexChanged">
<ItemTemplate>
<table width="100%">
<tr>
<td>
<%# Eval("Name") %>
</td>
<td>
<%# Eval("Population")%>
</td>
</tr>
</table>
</ItemTemplate>
</telerik:RadComboBox>
<telerik:RadComboBox ID="RadComboBox3" runat="server">
<ItemTemplate>
<table width="100%">
<tr>
<td>
<%# Eval("Name") %>
</td>
<td>
<%# Eval("Population")%>
</td>
</tr>
</table>
</ItemTemplate>
</telerik:RadComboBox>
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public int Population { get; set; }
}
public class State
{
public int Id { get; set; }
public int CountryId { get; set; }
public string Name { get; set; }
public int Population { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string Name { get; set; }
public int Population { get; set; }
}
public List<Country> Countries
{
get
{
return new List<Country>
{
new Country {Id = 1, Name = "United States", Population = 1000},
new Country {Id = 2, Name = "Canada", Population = 2000},
new Country {Id = 3, Name = "Mexico", Population = 3000}
};
}
}
public List<State> States
{
get
{
return new List<State>
{
new State {Id = 1, CountryId = 1, Name = "California", Population = 100},
new State {Id = 2, CountryId = 1, Name = "New York", Population = 200},
new State {Id = 3, CountryId = 2, Name = "Quebec", Population = 300},
new State {Id = 4, CountryId = 2, Name = "Ontario", Population = 400}
};
}
}
public List<City> Cities
{
get
{
return new List<City>
{
new City {Id = 1, StateId = 1, Name = "Los Angeles", Population = 10},
new City {Id = 2, StateId = 1, Name = "San Diego", Population = 20},
new City {Id = 3, StateId = 1, Name = "San Francisco", Population = 30},
new City {Id = 4, StateId = 1, Name = "San Joe", Population = 40},
new City {Id = 5, StateId = 2, Name = "New York", Population = 50},
new City {Id = 6, StateId = 2, Name = "Paterson", Population = 60},
new City {Id = 7, StateId = 2, Name = "Newark", Population = 70},
new City {Id = 8, StateId = 2, Name = "Smithtown", Population = 80},
};
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
RadComboBox1.DataSource = Countries;
RadComboBox1.DataValueField = "Id";
RadComboBox1.DataTextField = "Name";
RadComboBox1.DataBind();
RadComboBox1.Items.Insert(0, new RadComboBoxItem("Select Country", ""));
}
}
protected void RadComboBox1_SelectedIndexChanged(
object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
RadComboBox2.Items.Clear();
RadComboBox3.Items.Clear();
int countryId;
if (Int32.TryParse(e.Value, out countryId))
{
RadComboBox2.DataSource = States.Where(s => s.CountryId == countryId);
RadComboBox2.DataValueField = "Id";
RadComboBox2.DataTextField = "Name";
RadComboBox2.DataBind();
RadComboBox2.Items.Insert(0, new RadComboBoxItem("Select State", ""));
}
}
protected void RadComboBox2_SelectedIndexChanged(
object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
RadComboBox3.Items.Clear();
int stateId;
if (Int32.TryParse(e.Value, out stateId))
{
RadComboBox3.DataSource = Cities.Where(c => c.StateId == stateId);
RadComboBox3.DataValueField = "Id";
RadComboBox3.DataTextField = "Name";
RadComboBox3.DataBind();
RadComboBox3.Items.Insert(0, new RadComboBoxItem("Select City", ""));
}
}
I don't know about 'related' values, per sé; however you may need to develop that on your own.
Besides Telerik, if you don't mind using jQuery, here are a couple of plugins you can use for free to achieve the multi-column/header aspect:
mcDropdown jQuery Plug-in v1.3.1
Jquery Multi Column Selectbox
There are a few others you can take a peak at using this google search.
Helpful reference: jQuery

Gridview RowCommand not working

I am having problems trying to get a rowcommand event to fire in a gridview. I followed the code example from MSDNet but I cannot figure out why it is not working. The code is below. Thank you.
<asp:GridView ID="GridViewProducts" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="5" CellSpacing="1" DataKeyNames="Pkey"
DataSourceID="SqlDataSourceProducts" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCCCC" />
<PagerSettings PageButtonCount="20" />
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" >
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Interest">
<ItemTemplate>
<asp:DropDownList ID="ddlProductInterest" runat="server" SelectedValue='<%# Bind("ProductInterest") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>None</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="TestButton" Text="Button" CommandName="Test"
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="center" />
<ItemStyle HorizontalAlign="center" />
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
++Code Behind +++
Sub GridViewProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Test" Then
Dim index = Convert.ToInt32(e.CommandArgument)
Dim row = GridViewProducts.Rows(index)
Dim MyString As String = row.Cells(0).Text
strSQL = "INSERT INTO tblClosedProducts (" & _
"Product, ClosedBy, DateClosed " & _
") VALUES (" & _
"#Product, #ClosedBy, #DateClosed " & _
")"
Dim MyParameters1 As SqlParameter() = { _
New SqlParameter("#Product", SqlDbType.VarChar), _
New SqlParameter("#ClosedBy", SqlDbType.VarChar), _
New SqlParameter("#DateClosed", SqlDbType.SmallDateTime) _
}
MyParameters1(0).Value = row.Cells(0).Text
MyParameters1(1).Value = GetInfo.GetFullName(UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4)))
MyParameters1(2).Value = DateAdd("h", -1, Now())
objData.SQLExecuteNonQuery(strSQL, CommandType.Text, MyParameters1)
End If
End Sub
Your gridview doesnt have the event wired up in its markup.
Try adding in onrowcommand="GridViewProducts_RowCommand" so it looks like this:
<asp:GridView ID="GridViewProducts" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="5" CellSpacing="1" DataKeyNames="Pkey"
DataSourceID="SqlDataSourceProducts" ForeColor="Black" GridLines="Vertical"
onrowcommand="GridViewProducts_RowCommand">
#rtpHarry is correct, and that is a valid way to wire up the event. Another method of wiring the event would be to change the signature of your method in the code behind to add Handles Me.GridViewProducts.RowCommand to the end:
Sub GridViewProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles Me.GridViewProducts.RowCommand
protected void Add_Update_Remove_Row(int Index, string Operation)
{
//DataTable dt = (DataTable)ViewState["Table_BinaryPayment"];
int ID = Index;
Label lblddt = (Label)GridView1.Rows[Index].FindControl("Label2");
Label lblttm = (Label)GridView1.Rows[Index].FindControl("Label1");
Label lblid = (Label)GridView1.Rows[Index].FindControl("lblID");
Label lblaeamt = (Label)GridView1.Rows[Index].FindControl("lblamt");
Label lblprojID = (Label)GridView1.Rows[Index].FindControl("lblprojectID");
Label lblpaydetails = (Label)GridView1.Rows[Index].FindControl("lblpaydetails");
Label lblexpdate = (Label)GridView1.Rows[Index].FindControl("lblExpDate");
Label lblexpttime = (Label)GridView1.Rows[Index].FindControl("lblExpTime");
Label lblalloycodes = (Label)GridView1.Rows[Index].FindControl("lblalloycode");
Label lblalloyrates = (Label)GridView1.Rows[Index].FindControl("lblalloyRate");
Label lbladddelivered = (Label)GridView1.Rows[Index].FindControl("lbladdtodeliver");
Label lblEID = (Label)GridView1.Rows[Index].FindControl("lblEID");
ViewState["DispTime"] = lblttm.Text;
ViewState["ExpTime"] = lblexpttime.Text;
if (Operation == "Modify")
{
//lblchqNo.Text = txtchequeNO1.Text;
//lblchqDate.Text = txtchequeDate1.Text;
//lblAccountNo.Text = txtAccountNo.Text;
//lblBName.Text = txtBankName.Text;
lblddt.Text = txtdispdate.Text;
if (ddldisphr.SelectedItem.Text == "00" & ddldispmin.SelectedItem.Text == "00" & ddldispsec.SelectedItem.Text == "00")
{
lblttm.Text = ViewState["DispTime"].ToString();
}
else
{
lblttm.Text = (ddldisphr.SelectedItem.Text + ":" + ddldispmin.SelectedItem.Text + ":" + ddldispsec.SelectedItem.Text);
}
if (ddlexphr.SelectedItem.Text == "00" & ddlexpmin.Text == "00" & ddlexpsec.Text == "00")
{
lblexpttime.Text = ViewState["ExpTime"].ToString();
}
else
{
lblexpttime.Text = (ddlexphr.SelectedItem.Text + ":" + ddlexpmin.Text + ":" + ddlexpsec.Text);
}
lblaeamt.Text = txtadvPayment.Text;
lblpaydetails.Text = txtpaymentdetails.Text;
lblexpdate.Text = txtexpdate.Text;
lblalloycodes.Text = ddlalloycode.SelectedItem.Text;
lblalloyrates.Text = txtalloyrate.Text;
lbladddelivered.Text = txtaadtodel.Text;
//ExecuteProcedures ex = new ExecuteProcedures(4);
//string proc="Inse_Clientorder";
//ex.Parameters.Add("#dtPayment_Date", SqlDbType.DateTime, lblddt.Text);
//ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
//ex.Parameters.Add("#Enquiry_ID", SqlDbType.VarChar, ID );
//ex.Parameters.Add("#numAdvance_Amount", SqlDbType.Float , Convert.ToDouble(txtadvPayment.Text ));
//bool s = ex.InvokeProcedure(proc);
ExecuteProcedures ex = new ExecuteProcedures(12);
//string proc = "Inse_Clientorder123";
string proc = "Inse_Clientorder321";
ex.Parameters.Add("#dtPayment_Date", SqlDbType.DateTime, Convert.ToDateTime(lblddt.Text));
//if (ddldisphr.SelectedItem.Text == "00" & ddldispmin.SelectedItem.Text == "00" & ddldispsec.SelectedItem.Text == "00")
//{
// ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, ViewState["DispTime"]);
//}
//else
//{
// ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
//}
//if (ddlexphr.SelectedItem.Text == "00" & ddlexpmin.Text == "00" & ddlexpsec.Text == "00")
//{
// ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, ViewState["ExpTime"]);
//}
//else
//{
// ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, lblexpttime.Text);
//}
ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, lblexpttime.Text);
ex.Parameters.Add("#Advance_Payment_ID", SqlDbType.Int, Convert.ToInt32(lblid.Text));
ex.Parameters.Add("#numAdvance_Amount", SqlDbType.VarChar, lblaeamt.Text);
ex.Parameters.Add("#AlooyCode", SqlDbType.VarChar, lblalloycodes.Text);
ex.Parameters.Add("#numRate", SqlDbType.Float, Convert.ToDouble(lblalloyrates.Text));
ex.Parameters.Add("#vcrDescription", SqlDbType.VarChar, lbladddelivered.Text);
ex.Parameters.Add("#Client_Ordered_Projects_ID", SqlDbType.Int, Convert.ToInt32(lblprojID.Text));
ex.Parameters.Add("#Enquiry_ID", SqlDbType.Int, Convert.ToInt32(lblEID.Text));
ex.Parameters.Add("#dtExpectedPayment_Date", SqlDbType.DateTime, Convert.ToDateTime(lblexpdate.Text));
ex.Parameters.Add("#vcrPayment_Details", SqlDbType.VarChar, lblpaydetails.Text);
bool s = ex.InvokeProcedure(proc);
if (s == true)
{
CommonFunctions.Alert("Records Updated Successfully", this.Page);
}
else
{
CommonFunctions.Alert("Error In Updation", this.Page);
}
clear();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//if (e.CommandName == "Modify")
//{
// string strID = e.CommandArgument.ToString();
// strID = CommonFunctions.Encrypt(strID);
// Response.Redirect("Client_Order.aspx?Project_ID=" + strID);
//}
if (e.CommandName == "Modify")
{
string strID = e.CommandArgument.ToString();
int intRowIndex = ((GridViewRow)((LinkButton)e.CommandSource).Parent.Parent).RowIndex;
//Session[rowindex] = intRowIndex;
txtdispdate.Text = GridView1.Rows[intRowIndex].Cells[6].Text;
string strdisp = ((ddldisphr.SelectedItem.Text) + ":" + (ddldispmin.SelectedItem.Text) + ":" + (ddldispsec.SelectedItem.Text)).ToString();
lbltime.Text = GridView1.Rows[intRowIndex].Cells[7].Text;
Label lblClienorderiid = (Label)GridView1.Rows[intRowIndex].FindControl("lblcLOID");
Label lbledate = (Label)GridView1.Rows[intRowIndex].FindControl("Label2");
Label lbletime = (Label)GridView1.Rows[intRowIndex].FindControl("Label1");
Label lbliid = (Label)GridView1.Rows[intRowIndex].FindControl("lblID");
Label lblaamt = (Label)GridView1.Rows[intRowIndex].FindControl("lblamt");
Label lblEID = (Label)GridView1.Rows[intRowIndex].FindControl("lblEID");
Label lblprojID = (Label)GridView1.Rows[intRowIndex].FindControl("lblprojectID");
Label lblpaydetails = (Label)GridView1.Rows[intRowIndex].FindControl("lblpaydetails");
Label lblexpdate = (Label)GridView1.Rows[intRowIndex].FindControl("lblExpDate");
Label lblexpttime = (Label)GridView1.Rows[intRowIndex].FindControl("lblExpTime");
Label lblalloycodes = (Label)GridView1.Rows[intRowIndex].FindControl("lblalloycode");
Label lblalloyrates = (Label)GridView1.Rows[intRowIndex].FindControl("lblalloyRate");
Label lbladddelivered = (Label)GridView1.Rows[intRowIndex].FindControl("lbladdtodeliver");
ViewState["Index"] = intRowIndex;
ViewState["CommandName"] = e.CommandName;
txtdispdate.Text = lbledate.Text;
lbltime.Text = lbletime.Text;
txtadvPayment.Text = lblaamt.Text;
ddlalloycode.SelectedItem.Text = lblalloycodes.Text;
txtalloyrate.Text = lblalloyrates.Text;
txtaadtodel.Text = lbladddelivered.Text;
txtpaymentdetails.Text = lblpaydetails.Text;
txtexpdate.Text = lblexpdate.Text;
lblexptimess.Text = lblexpttime.Text;
pnl2.Visible = true;
//lbltime.Text = lbltm.Text;
//Add_Update_Remove_Row( intRowIndex , e.CommandName);
}
else if (e.CommandName == "Del")
{
string strID = e.CommandArgument.ToString();
string strSql = "Delete from Client_Order where Client_ID = " + strID;
string str_query = "Update Enquiry set OrderExecuted='No' where Enquiry_ID = " + strID;
//string str_query = "delete from Enquiry where Enquiry_ID = " + strID;
Dentry de = new Dentry();
de.RunCommand(strSql);
de.RunCommand(str_query);
Bind_Data();
}
else if(e.CommandName =="Invoice")
{
string strID = e.CommandArgument.ToString();
strID = CommonFunctions.Encrypt(strID);
string strType = CommonFunctions.Encrypt("New");
Response.Redirect("New_Order_Project_Invoice_Entry.aspx?Project_ID=" + strID + "&Type=" + strType);
}
else if (e.CommandName == "Delivered")
{
string strId = e.CommandArgument.ToString();
string str_query = "Update Enquiry set vcrDelivered='Yes' where Enquiry_ID=" + strId;
Dentry de = new Dentry();
de.RunCommand(str_query);
Bind_Data();
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");
lnk.Attributes.Add("onClick", "return confirm('Are you sure to delete this record?');");
}
}
Enable View State= true will solve your problem

Resources