multiply the gridview columns - c#

I will post you my code and i will explain what i want to do
<div>
<div>
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="hdValue" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="btnMove" runat="server" Text="Add To Cart" OnClick="btnMove_Click" />
</div>
<div>
<asp:GridView ID="gridView2" runat="server">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="tbQty" runat="server" Width="25px"
MaxLength="3" />
</ItemTemplate>
<ItemStyle Width="25px" HorizontalAlign="Center"/>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:Button ID="Button1" runat="server" Text="Find the total" />
<asp:Label ID="Label7" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<br />
<br />
</div>
and the theo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class theo : System.Web.UI.Page
{
const string key = "MyDataSource5";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
if (Session[key] == null)
{
gridView1.DataSource = GetDataSource();
gridView1.DataBind();
}
else
{
gridView1.DataSource = (DataTable)Session[key];
gridView1.DataBind();
}
}
protected DataTable GetDataSource()
{
try
{
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
dt.Rows.Add("2", "Arable Land", 0.1);
dt.Rows.Add("3", "Foothills of the mountains", 1.5);
dt.Rows.Add("4", "Industrial Land", 0.1);
dt.Rows.Add("5", "Rolling Farmland", 0.5);
Session[key] = dt;
return dt;
}
catch
{
return null;
}
}
protected void btnMove_Click(object sender, EventArgs e)
{
try
{
DataTable dtMain = Session[key] as DataTable;
//copy the schema of source table
DataTable dtClone = dtMain.Clone();
foreach (GridViewRow gv in gridView1.Rows)
{
CheckBox chk = gv.FindControl("chkSelect") as CheckBox;
HiddenField hdValue = gv.FindControl("hdValue") as HiddenField;
if (chk.Checked)
{
//get only the rows you want
DataRow[] results = dtMain.Select("ID=" + hdValue.Value + "");
//populate new destination table
foreach (DataRow dr in results)
{
dtClone.ImportRow(dr);
}
}
gridView2.DataSource = dtClone;
gridView2.DataBind();
}
}
catch
{
BindGridView();
}
}
}
In this code when i check for example 2 choices from gridview 1 and click the button add to cart then these 2 choices are moving to the second gridview. As you see,I have a textbox for the quantity. I would like when i give the quantity to multiply it with the price.With the button 'find the total' i want to give me the result in the text box.How can i do that?

one simple solution may be useful to you.
protected void Button1_Click(object sender, EventArgs e)
{
int itemCount;
decimal itemPrice, itemTotal;
itemTotal = 0;
itemCount = 0;
itemPrice = 0;
foreach(GridViewRow gridView2Row in gridView2.Rows)
{
TextBox tbCount = gridView2Row.Cells[0].Controls[1] as TextBox;
itemCount = Convert.ToInt32(tbCount.Text);
itemPrice = Convert.ToDecimal(gridView2Row.Cells[3].Text);
itemTotal = itemTotal + (itemCount * itemPrice);
}
TextBox1.Text = itemTotal.ToString();
}

Related

I'm deleting rows from gridview but all data in the table is deleted

I want to add and delete rows dynamically in Gridview. Adding is successful. When I delete the row, the row is deleted successfully. But the data entered in other rows is cleared.
I want to delete rows. I also want to prevent the deletion of previously entered data.
Default.aspx
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-CssClass="row-edit" HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandName="Select" runat="server"><i class="fas fa-times"></i></asp:LinkButton>
</ItemTemplate>
<ControlStyle CssClass="row-edit"></ControlStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
Default.aspx.cs
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
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++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
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;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
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++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
int indis = Gridview1.SelectedIndex;
GridViewRow satir = Gridview1.Rows[indis];
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow[] _row = dtCurrentTable.Select("RowNumber=" + satir.Cells[0].Text);
foreach (DataRow row in _row)
{
row.Delete();
}
dtCurrentTable.AcceptChanges();
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
Here's the problem
(It won't let me paste it as a flat image.)
My problem
Well, we are deleting one row at a time, right?
Ok, based on feedback, need/want this for the markup:
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="cmdDel" runat="server" Text="Delete" OnClick="cmdDel_Click"
OnClientClick="return confirm('Delete this row? (cannot undo)');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
<asp:Button ID="cmdSave" runat="server" Text="Save Grid to Table" Style="margin-left:30px" OnClick="cmdSave_Click"/>
And the code looks like:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateTable();
AddRow();
LoadGrid();
ViewState["MyTable"] = dt;
}
else
{
dt = (DataTable)ViewState["MyTable"];
}
}
void CreateTable()
{
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns[0].AutoIncrementSeed = 1;
dt.Columns[0].AutoIncrementStep = 1;
dt.Columns[0].AutoIncrement = true;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
}
void AddRow()
{
DataRow dr = dt.NewRow();
dr["Column1"] = "";
dr["Column2"] = "";
dr["Column3"] = "";
dt.Rows.Add(dr);
}
void LoadGrid()
{
// Gridview1.Columns.Clear();
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SaveData();
AddRow();
LoadGrid();
}
void SaveData()
{
// move grid changes back to table
foreach (GridViewRow gvRow in Gridview1.Rows)
{
//extract the TextBox values
DataRow dr = dt.Rows[gvRow.RowIndex];
dr["Column1"] = ((TextBox)gvRow.FindControl("TextBox1")).Text;
dr["Column2"] = ((TextBox)gvRow.FindControl("TextBox2")).Text;
dr["Column3"] = ((TextBox)gvRow.FindControl("TextBox3")).Text;
}
dt.AcceptChanges();
}
protected void cmdSave_Click(object sender, EventArgs e)
{
SaveData();
}
protected void cmdDel_Click(object sender, EventArgs e)
{
Button cmdDel = (Button)sender;
GridViewRow gvRow = (GridViewRow)cmdDel.Parent.Parent;
dt.Rows[gvRow.RowIndex].Delete();
dt.AcceptChanges();
LoadGrid();
}
Of course the save button in real use would be "submit" and move on to the next web page, or whatever task the user is working on.
And I assume this is just for learning, since a table just sitting in memory has next to zero use. I would assume that the table would be from a database, else this setup not all that much use.

How to achieve bulk save in Gridview using ASP.NET with C#

I have got a Gridview which gets populated with multiple rows as follows where user is allowed to edit Alternate names for the viewed rows after he can bulk save the edited columns.
I tried achieving this using Edit template but I could not achieve this because when the user tries to edit the next row immediately the previous "edited" column contents are erased back to original.
How can I achieve this using gridview
On edit action of the GridView, your change happens only on your browser (client side) until you save the change of current row. You need to save the row and refresh GridView to begin editing the next row.
The typical implementation is to place two button on Edit template - Cancel and Save button to commit the change of the edited row. When clicking on the save button, your postback event will be picked up on server side code (with event argument e that contain which row was on edit and row data that you updated). You save the data to database and refresh the GridView. At that moment, you should be able to see the GridView with updated content. You are ready to click on the Edit button of the next row.
Use this and Edit According to you this is working for me perfectly.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("[id$=txtRecievedDate]").datepicker({
showOn: 'button',
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif'
});
});
</script>
<style type = "text/css">
input[type=text], select{background-color:#FFFFD2; border:1px solid #ccc}
</style>
</head>
<body style = "font-family:Arial;font-size:10pt">
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
DataKeyNames = "id" onrowdatabound="gvCustomers_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="SelectEdit"></asp:Label>
<asp:CheckBox ID = "chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
<asp:TextBox ID="txtID" runat="server" Text='<%# Eval("id") %>' ReadOnly="true" Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cartridge Set No" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>'></asp:Label>
<asp:TextBox ID="txtCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>' ReadOnly="true" Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID = "lblcurrentstatus" runat="server" Text='<%# Eval("currentstatus") %>'></asp:Label>
<asp:Label ID = "lblstatus" runat="server" Text='<%# Eval("status") %>' Visible = "false"></asp:Label>
<asp:DropDownList ID="ddlstatus" runat="server" Visible = "false">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="date Recieved" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("dateRecieved") %>'></asp:Label>
<asp:TextBox ID="txtRecievedDate" runat="server" Text='<%# Eval("dateRecieved") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server" Text='<%# Eval("comments") %>'></asp:Label>
<asp:TextBox ID="txtComments" runat="server" Text='<%# Eval("comments") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick = "Update" Visible = "false"/>
</form>
</body>
</html>
CS file
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
SqlCommand cmd = new SqlCommand("SELECT [Id],[CartridgeSetNo],[status] ,[dateRecieved],[Comments] ,case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as currentstatus FROM DrugAllocate ");
gvCustomers.DataSource = this.ExecuteQuery(cmd, "SELECT");
gvCustomers.DataBind();
}
private DataTable ExecuteQuery(SqlCommand cmd, string action)
{
string conString = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
switch (action)
{
case "SELECT":
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
case "UPDATE":
con.Open();
cmd.ExecuteNonQuery();
con.Close();
break;
}
return null;
}
}
protected void Update(object sender, EventArgs e)
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
SqlCommand cmd = new SqlCommand("UPDATE DrugReceipt SET Comments=#Comments, dateRecieved=#dateRecieved , status = #status where Id = #Id");
cmd.Parameters.AddWithValue("#Comments", row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text);
string status = row.Cells[3].Controls.OfType<DropDownList>().FirstOrDefault().SelectedItem.Value;
if (status == "Received and Usable")
{
status="0";
}
if (status == "Received but not usable")
{
string comments=row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text;
status = "1";
if (comments == "")
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('comment is mendatry');", true);
break;
}
}
if (status == "Not Received")
{
status = "2";
}
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#dateRecieved", row.Cells[4].Controls.OfType<TextBox>().FirstOrDefault().Text);
cmd.Parameters.AddWithValue("#Id", gvCustomers.DataKeys[row.RowIndex].Value);
this.ExecuteQuery(cmd, "UPDATE");
}
}
}
btnUpdate.Visible = false;
this.BindGrid();
}
public DataSet GetYesNoValue(string ColumnName)
{
DataTable dtVal = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = ColumnName;
dtVal.Columns.Add(column);
DataSet dsVal = new DataSet();
dtVal.Rows.Add("Received and Usable");
dtVal.Rows.Add("Received but not usable");
dtVal.Rows.Add("Not Received");
dsVal.Tables.Add(dtVal);
return dsVal;
}
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (sender as CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (gvCustomers.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 1; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked )
{
chkAll.Checked = false;
}
}
}
}
btnUpdate.Visible = isUpdateVisible;
}
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd = new SqlCommand("SELECT status, case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as statuscurrent FROM DrugAllocate");
DropDownList ddlstatus = (e.Row.FindControl("ddlstatus") as DropDownList);
ddlstatus.DataSource = this.ExecuteQuery(cmd, "SELECT");
string country = (e.Row.FindControl("lblstatus") as Label).Text;
DataSet ds = new DataSet();
ds = GetYesNoValue("suppStatus");
DataTable dt = new DataTable();
dt = ds.Tables[0];
ddlstatus.DataSource = dt;
ddlstatus.DataTextField = "suppStatus";
ddlstatus.DataValueField = "suppStatus";
ddlstatus.DataBind();
try
{
ddlstatus.Items.FindByValue(country).Selected = true;
}
catch { }
}
}
}

DataBinding:System.Data.DataRowView does not contain a property with the name Quantity

The Back End Code
Please help to identify the problem
There is a data binding error in Quantity Field in the gridview that contains a dropdownlist which is causing an error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Webpages_Cart : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConn"].ConnectionString);
DataTable dtCart = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
string id;
if (Session["bool"] != null)
{
bool ab = (bool)Session["bool"];
id = (string)Request.QueryString["Id"];
if (ab == true)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "Select Name,Money from Image where Id=" + id;
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (Session["Cart"] == null)
{
da.Fill(dtCart);
Session["Cart"] = dtCart;
con.Close();
FillCart();
CreateCart();
}
else
{
DataTable data = Session["Cart"] as DataTable;
da.Fill(dtCart);
dtCart.Merge(data);
dtCart.AcceptChanges();
Session["Cart"] = dtCart;
con.Close();
FillCart();
}
}
else
{
if (Session["Cart"] != null)
{
dtCart = Session["Cart"] as DataTable;
FillCart();
}
}
if(Session["Cart"]==null)
{
FillCart();
CreateCart();
}
Session["bool"] = false;
}
}
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataTable dtCart = (DataTable)Session["Cart"];
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
if (row != null)
{
int quantity = Convert.ToInt32(((DropDownList)(row.FindControl("ddlQuantity"))).SelectedValue);
int index = Convert.ToInt32(((DropDownList)(row.FindControl("ddlQuantity"))).SelectedIndex);
int price = Convert.ToInt32(dtCart.Rows[row.RowIndex]["Price"]);
dtCart.Rows[row.RowIndex].SetField("Quantity", (quantity));
dtCart.Rows[row.RowIndex].SetField("Subtotal", (quantity * price));
GridView1.DataSource = dtCart;
GridView1.DataBind();
Session["Cart"] = dtCart;
}
}
catch (Exception ex)
{
Response.Redirect("ErrorPa.aspx?Id="+ex.Message.ToString());
}
}
private void CreateCart()
{
dtCart = new DataTable();
dtCart.Columns.Add("Sr No", typeof(int));
dtCart.Columns.Add("Name", typeof(string));
dtCart.Columns.Add("Price", typeof(int));
//dtCart.Columns.Add("Image");
dtCart.Columns.Add("Quantity", typeof(int));
dtCart.Columns.Add("Subtotal", typeof(int));
}
private void FillCart()
{
try
{
if (Session["Cart"] != null)
{
dtCart = (DataTable)Session["Cart"];
}
DataTable dtSelProducts = (DataTable)Session["dtSelectProduct"];
if (Session["dtSelectProduct"] != null)
{
foreach (DataRow dr in dtSelProducts.Rows)
{
dtCart.Rows.Add(Convert.ToInt32(dtCart.Rows.Count + 1), Convert.ToString(dr["Name"]), Convert.ToInt32(dr["Price"]), 1, Convert.ToInt32(dr["Price"]));
}
Session["dtSelectProduct"] = null;
}
Session["Cart"] = dtCart;
GridView1.DataSource = dtCart;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Redirect("ErrorPa.aspx?Id="+ex.Message.ToString());
}
}
protected void imgDeleteProduct_Click(object sender, ImageClickEventArgs e)
{
try
{
DataTable dtCart = (DataTable)Session["Cart"];
int SrNo = Convert.ToInt32(((ImageButton)sender).CommandArgument);
dtCart.Rows.RemoveAt((SrNo - 1));
dtCart = RegenerateDataTable(dtCart);
GridView1.DataSource = dtCart;
GridView1.DataBind();
Session["Cart"] = dtCart;
if (dtCart.Rows.Count == 0)
{
btnProceed.Enabled = false;//dvSendOrder.Visible = false;
}
Label lblMaster = (Label)this.Master.FindControl("lblCartValue");
//if (lblMaster != null)
//{
// if (Session["Cart"] == null)
// {
// lblMaster.Text = "(0)";
// }
// else
// {
// DataTable dt = (DataTable)Session["Cart"];
// lblMaster.Text = "(" + Convert.ToString(dt.Rows.Count) + ")";
// }
//}
}
catch (Exception ex)
{
Response.Redirect("ErrorPa.aspx?Id="+ex.Message.ToString());
}
}
private DataTable RegenerateDataTable(DataTable dt)
{
int srno = 0;
DataTable dtDup = dt.Clone();
try
{
foreach (DataRow row in dt.Rows)
{
DataRow drNew = dtDup.NewRow();
srno += 1;
drNew[0] = srno;
drNew[1] = row[1];
drNew[2] = row[2];
drNew[3] = row[3];
drNew[4] = row[4];
drNew[5] = row[5];
drNew[6] = row[6];
dtDup.Rows.Add(drNew);
}
}
catch (Exception ex)
{
Response.Redirect("ErrorPa.aspx?Id="+ex.Message.ToString());
}
return dtDup;
}
}
the Front End
The Quantity Field in GridView is causing error as the data is not binding
<%# Page Title="Cart" Language="C#" ErrorPage="~/Webpages/ErrorPa.aspx" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Cart.aspx.cs" Inherits="Webpages_Cart" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<br /><br />
<h1 class="Contact">Cart</h1>
<%-- <asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:ImageField HeaderText="Image" DataImageUrlField="Image" ReadOnly="True">
</asp:ImageField>--%>
<asp:GridView ID="GridView1" HorizontalAlign="Center" ShowHeaderWhenEmpty="true" runat="server" RowStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" EnableModelValidation="True"
AutoGenerateColumns="False" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" EmptyDataText="There are no items in cart.">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField HeaderText="Sr No"/>
<%--<asp:BoundField HeaderText="ID" DataField="ProductID" />--%>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Price" DataField="Money" />
<%--<asp:ImageField HeaderText="Image" DataImageUrlField="Image" />--%>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="ddlQuantity" runat="server" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged" AutoPostBack="True" SelectedValue='<%# Bind("Quantity")%>'>
<asp:ListItem Value="1" Text="1"></asp:ListItem>
<asp:ListItem Value="2" Text="2"></asp:ListItem>
<asp:ListItem Value="3" Text="3"></asp:ListItem>
<asp:ListItem Value="4" Text="4"></asp:ListItem>
<asp:ListItem Value="5" Text="5"></asp:ListItem>
<asp:ListItem Value="6" Text="6"></asp:ListItem>
<asp:ListItem Value="7" Text="7"></asp:ListItem>
<asp:ListItem Value="8" Text="8"></asp:ListItem>
<asp:ListItem Value="9" Text="9"></asp:ListItem>
<asp:ListItem Value="10" Text="10"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Subtotal" DataField="Subtotal" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDeleteProduct" CommandArgument='<%# Eval("SrNo") %>' ToolTip="Remove"
OnClientClick="return confirm('Are you sure you want to remove this product?');" CausesValidation="False"
OnClick="imgDeleteProduct_Click" ImageUrl="images/delete_icon.png"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<PagerStyle CssClass="pgr" />
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:Button ID="btnProceed" runat="server" Text="Button" />
</asp:Content>

c# asp.net, dynamic drop list population after event, Save data in dynamic Gridview

I have made a simple code to show you my problem.
I have a dynamic gridview with a variety of controls.
I want the 2nd dropdown list to get populated with specific data which depend on the selected index of the first drop down list.
So for instance let's say we have droplist1 with 4 options so droplist1.SelectedIndex is 1,2,3,4.
When i select (option)2 there's the event triggered on select and droplist2 goes droplist2.datasource = based on droplist1.SelectedIndex , ( i hope you understand).
I have managed to populate the droplist2 after the droplist1.SelectedIndex event BUT i can't get the value to be saved...
I saw on the debugger that it goes till one point but after that the line appears empty on my screen...
Here's my HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" ClientIDMode="Static" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 337px">
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Column1">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="Category" DataTextField="ExpenseCategoryName" DataValueField="ExpenseCategoryName" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="Category" runat="server" ConnectionString="<%$ ConnectionStrings:Expenses_NewConnectionString %>" SelectCommand="SELECT [ExpenseCategoryName] FROM [ExpenseCategories]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column2">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
and my C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setInitialRow();
}
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
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 ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = ddl1.SelectedValue;
dtCurrentTable.Rows[i - 1]["Column2"] = ddl2.SelectedValue;
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 ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
try
{
ddl1.Text = dt.Rows[i]["Column1"].ToString();
ddl2.Text = dt.Rows[i]["Column2"].ToString();
}
catch (Exception ex)
{ }
rowIndex++;
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[2].FindControl("DropDownList2");
FillDropDownList(ddl2);
}
}
}
private ArrayList GetData()
{
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Item1", "1"));
arr.Add(new ListItem("Item2", "2"));
arr.Add(new ListItem("Item3", "3"));
arr.Add(new ListItem("Item4", "4"));
arr.Add(new ListItem("Item5", "5"));
return arr;
}
private void FillDropDownList(DropDownList ddl)
{
ArrayList arr = GetData();
foreach (ListItem item in arr)
{
ddl.Items.Add(item);
}
}
}
}

Gridview Paging ASP.NET with Pager Panel outside Gridview

This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>

Categories

Resources