Counter doesn't increment - asp.net

Relatively new to coding, so there might be a clear mistake in the code. What I am trying to do is have a counter that increases by one each time a new product is added to the basket.
When the program is run, its default value is 0, when the you click on the first product to add to the basket, it increases to 1, however, if you add any more products it sticks at 1 instead of increasing each time.
I have included the code below - is there an obvious mistake I am over looking being a novice (I'll be the first to attempt that ha!). No error message is thrown at any point.
protected void BtnAddToBasket_Click(object sender, EventArgs e)
{
string ProductID = Convert.ToInt16((((Button)sender).CommandArgument)).ToString();
string ProductStock = "1";
DataListItem currentItem = (sender as Button).NamingContainer as DataListItem;
Label lblAvailableStock = currentItem.FindControl("lblAvailableStock") as Label;
if (Session["MyBasket"] != null)
{
DataTable dt = (DataTable)Session["My Basket"];
var checkProduct = dt.AsEnumerable().Where(r => r.Field<string>("ProductID") == ProductID);
if (checkProduct.Count() == 0)
{
string query = "SELECT * FROM Product WHERE ProductID = " + ProductID + "";
DataTable dtProduct = GetData(query);
DataRow dr = dt.NewRow();
dr["ProductID"] = ProductID;
dr["ProductName"] = Convert.ToString(dtProduct.Rows[0]["ProductName"]);
dr["ProductDescription"] = Convert.ToString(dtProduct.Rows[0]["ProductDescription"]);
dr["ProductPrice"] = Convert.ToString(dtProduct.Rows[0]["ProductPrice"]);
dr["ProductStock"] = ProductStock;
dr["ProductImageUrl"] = Convert.ToString(dtProduct.Rows[0]["ProductImageUrl"]);
dr["AvailableStock"] = lblAvailableStock;
dt.Rows.Add(dr);
Session["MyBasket"] = dt;
btnShoppingBasket.Text = dt.Rows.Count.ToString();
}
}
else
{
string query = "SELECT * FROM Product WHERE ProductID =" + ProductID + "";
DataTable dtProduct = GetData(query);
DataTable dt = new DataTable();
dt.Columns.Add("ProductID", typeof(string));
dt.Columns.Add("ProductName", typeof(string));
dt.Columns.Add("ProductDescription", typeof(string));
dt.Columns.Add("ProductPrice", typeof(string));
dt.Columns.Add("ProductStock", typeof(string));
dt.Columns.Add("ProductImageUrl", typeof(string));
dt.Columns.Add("AvailableStock", typeof(string));
DataRow dr = dt.NewRow();
dr["ProductID"] = ProductID;
dr["ProductName"] = Convert.ToString(dtProduct.Rows[0]["ProductName"]);
dr["ProductDescription"] = Convert.ToString(dtProduct.Rows[0]["ProductDescription"]);
dr["ProductPrice"] = Convert.ToString(dtProduct.Rows[0]["ProductPrice"]);
dr["ProductStock"] = ProductStock;
dr["ProductImageUrl"] = Convert.ToString(dtProduct.Rows[0]["ProductImageUrl"]);
dr["AvailableStock"] = lblAvailableStock;
dt.Rows.Add(dr);
Session["My Basket"] = dt;
btnShoppingBasket.Text = dt.Rows.Count.ToString();
}
}
Counter

From what I see it appears that you create new basket every time an item is added into the basket. The little mistake is that you use different names of saved basket entry in session:
if (Session["MyBasket"] != null)
This will be false first time so it goes into else block.
Session["My Basket"] = dt;
Here you store new DataTable with different key. So the next time the if statement will still be false. So just make sure that the name is consistent. "MyBasket" != "My Basket"

Fixed where "MyBasket" was "My Basket"; reduced code duplication. The misspelling is a compelling reason to use constants instead of string literals.
protected void BtnAddToBasket_Click(object sender, EventArgs e)
{
string ProductID = Convert.ToInt16((((Button)sender).CommandArgument)).ToString();
string ProductStock = "1";
DataListItem currentItem = (sender as Button).NamingContainer as DataListItem;
Label lblAvailableStock = currentItem.FindControl("lblAvailableStock") as Label;
if (Session["MyBasket"] == null)
{
DataTable dt = new DataTable();
dt.Columns.Add("ProductID", typeof(string));
dt.Columns.Add("ProductName", typeof(string));
dt.Columns.Add("ProductDescription", typeof(string));
dt.Columns.Add("ProductPrice", typeof(string));
dt.Columns.Add("ProductStock", typeof(string));
dt.Columns.Add("ProductImageUrl", typeof(string));
dt.Columns.Add("AvailableStock", typeof(string));
}
DataTable dt = (DataTable)Session["MyBasket"];
var checkProduct = dt.AsEnumerable().Where(r => r.Field<string>("ProductID") == ProductID);
if (checkProduct.Count() == 0)
{
string query = "SELECT * FROM Product WHERE ProductID = " + ProductID + "";
DataTable dtProduct = GetData(query);
DataRow dr = dt.NewRow();
dr["ProductID"] = ProductID;
dr["ProductName"] = Convert.ToString(dtProduct.Rows[0]["ProductName"]);
dr["ProductDescription"] = Convert.ToString(dtProduct.Rows[0]["ProductDescription"]);
dr["ProductPrice"] = Convert.ToString(dtProduct.Rows[0]["ProductPrice"]);
dr["ProductStock"] = ProductStock;
dr["ProductImageUrl"] = Convert.ToString(dtProduct.Rows[0]["ProductImageUrl"]);
dr["AvailableStock"] = lblAvailableStock;
dt.Rows.Add(dr);
Session["MyBasket"] = dt;
btnShoppingBasket.Text = dt.Rows.Count.ToString();
}
}

Related

if a variable or object of type var is null then how to assign a value to it

what i am trying to do is ,if row is null then how to programitaclly assign a new row to it
var row = (from obj in _objdb.tbl123 where obj.cus_id == hidCusRowId.Value select obj).ToList();
if (row == null)
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
TextBox objtxt = this.Master.FindControl("ContentPlaceHolder1").FindControl("txt0" ) as TextBox;
TextBox objtxtsize = this.Master.FindControl("ContentPlaceHolder1").FindControl("txts0") as TextBox;
dt.Columns.Add(objtxt.Text);
dr[0] = objtxtsize.Text;
List<string> lt = new List<string>();
lt.Add(objtxtsize.Text);
row.Add(lt.ToList());
}
GridView1.DataSource = row;
GridView1.DataBind();
an error is occured on row.add(lt.ToList())....

Asp.net - DropDownLists in GridView

I was trying to make a column of DropDownLists in GridView from the C# code, to no avail. Here is the code I use:
var manager=Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add("Email", typeof(String));
dt.Columns.Add("Username", typeof(String));
dt.Columns.Add("Roles", typeof(DropDownList));
var a = manager.Users.ToArray();
for (int i = 0; i < a.Length; i++ )
{
dr = dt.NewRow();
dr["Email"] = a[i].Email;
dr["Username"] = a[i].UserName;
DropDownList lista = new DropDownList();
var b = manager.Users.ToArray();
lista.DataSource = b;
lista.DataBind();
dr["Roles"] = (DropDownList)lista;
dt.Rows.Add(dr);
}
GridView1.AutoGenerateSelectButton = true;
dt.AcceptChanges();
GridView1.DataSource = dt;
GridView1.DataBind();
The first 2 colums show up, the last (which should have DropDownLists) does not. Why?

how to add data in the row from arraylist in asp.net?

i have a database..i am getting my database values in myarraylist..now i want to add this in my datatable column and finally bind it to gridview and show data in webpage..
mycodebehind page
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id", Type.GetType("System.String"));
dt.Columns.Add("Problem Name", Type.GetType("System.String"));
dt.Columns.Add("Status", Type.GetType("System.String"));
for (int i = 0; i < 2; i++)
{
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM usertable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
i have problem in the for loop ..here how i will add rows and values to the columns from arraylist...
Do you mean something like this?
for (int i = 0; i < myArrayList.Count; i++)
{
var row = dt.NewRow();
row[0] = ((DataRow)myArrayList[i])[0];
row[1] = ((DataRow)myArrayList[i])[1];
row[2] = ((DataRow)myArrayList[i])[2];
dt.Rows.Add(row);
}
where indexes 0,1,2... can be replaced by column names "User Id", "Problem Name" and "Status"

Data is not filling in dataview

I am trying to bind my repeater with dataview but it is not showing me data in dataview when i see it through breakpoint
private void Get_Data()
{
String File = Server.MapPath("BlogContent.xml");
DataSet ds = new DataSet();
ds.ReadXml(File);
DataView dv = new DataView(ds.Tables[0]);
DataTable dt = dv.Table;
ViewState.Add("Mytable", dt);
}
private void Bind_Data(int take, int pageSize)
{
PagedDataSource page = new PagedDataSource();
page.AllowCustomPaging = true;
page.AllowPaging = true;
DataTable dtv = (DataTable)ViewState["Mytable"];
DataView dv = new DataView();
dv = dtv.DefaultView;
dv.RowFilter = "id>=" + pageSize + " AND " + "id<=" + take;
page.DataSource = dv;
page.PageSize = psize;
Repeater1.DataSource = page;
Repeater1.DataBind();
if (!IsPostBack)
{
int rowcount = dtv.Rows.Count;
CreatePagingControl(rowcount);
}
}
PagedDataSource page = new PagedDataSource();
page.AllowCustomPaging = true;
page.AllowPaging = true;
DataTable dtv = (DataTable)ViewState["Mytable"];
DataView dv = new DataView();
dv = dtv.DefaultView;
dv.RowFilter = "id>=" + pageSize + " AND " + "id<=" + take;
page.DataSource = dv;
page.PageSize = psize;
Repeater1.DataSource = page;
Repeater1.DataBind();
if (!IsPostBack)
{
int rowcount = dtv.Rows.Count;
CreatePagingControl(rowcount);
}
please check it and tell me where i am going wrong.. I try to add paging in repeater control the number of paging display well but data is not fetching in dataview . When i check my datatable it is filling but when it comes to dataview shows me nothng
I got the answers.. The order of id in my xml was not in correct In my xml the id of each node is like
5
3
4
1
2
I do it correct
1
2
3
4
5
and it is working now ....

Update one cell after adding the new row with same values in gridview

I want to make shopping cart Datatable, I wrote the following code here to make the list of products
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
dt.Constraints.Add("Proid_PK", dt.Columns[0], true);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
return dt;
}
It binds the data fine with no problem, but where I insert the same row with same value it inserted in new record in the gridview, I don't want it like that I want update just one cell (I mean when I add new record with same values I want Quantity value on increase without adding new record in gridview) like I mark on the image
after long testing and googleing i finally get it done , here the code i used
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataView dv = dt.DefaultView;
dv.Sort = "ProName";
int found;
string Proname;
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
Proname = dr[0].ToString();
found = dv.Find(Proname);
if (found != -1)
{
foreach (DataRow pro in dt.Rows)
{
for (int x = 0; x < dt.Rows.Count; x++)
{
if (dt.Rows[x]["ProName"].ToString()==Proname)
{
dt.Rows[x]["quantity"] = Convert.ToInt16(dt.Rows[x]["quantity"]) + quantity;
}
}
}
}
}
}
return dt;
}
You could use LINQ:
DataTable dt = new DataTable("products");
dt.Columns.Add("ProName", typeof(string));
dt.Columns.Add("odate", typeof(DateTime));
dt.Columns.Add("ocountry", typeof(string));
dt.Columns.Add("oarea", typeof(string));
dt.Columns.Add("oaddress", typeof(string));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("price", typeof(decimal));
dt.Columns.Add("SubTotal", typeof(decimal));
DataRow dr1 = dt.NewRow();
dr1[0] = "test";
dr1[1] = new DateTime(2005, 5, 15);
dr1[2] = "US";
dr1[3] = "test area";
dr1[4] = "555";
dr1[5] = 1;
dr1[6] = 5.25;
dr1[7] = 5.25 * 1;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "test";
dr2[1] = new DateTime(2005, 5, 15);
dr2[2] = "US";
dr2[3] = "test area";
dr2[4] = "555";
dr2[5] = 3;
dr2[6] = 5.25;
dr2[7] = 5.25 * 3;
dt.Rows.Add(dr2);
var shoppingCart = from r in dt.AsEnumerable()
group r by new
{
ProName = r.Field<string>("ProName"),
odate = r.Field<DateTime>("odate"),
ocountry = r.Field<string>("ocountry"),
oarea = r.Field<string>("oarea"),
oaddress = r.Field<string>("oaddress"),
price = r.Field<decimal>("price")
} into g
select new
{
g.Key.ProName,
g.Key.odate,
g.Key.ocountry,
g.Key.oarea,
g.Key.oaddress,
g.Key.price,
quantity = g.Sum(s1 => s1.Field<int>("quantity")),
SubTotal = g.Sum(s2 => s2.Field<decimal>("SubTotal"))
};
foreach (var p in shoppingCart)
{
Console.WriteLine("Product: {0}, Quantity: {1}, Subtotal: {2}", p.ProName, p.quantity, p.SubTotal);
}
Results:
Product: test, Quantity: 4, Subtotal: 21.00

Resources