MasterPage Code:
public Label OnlbCartCountMasterPage {
get { return this.chartlabel; }
}
Index.aspx Code
String cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string cartQuantity;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadList();
}
if (Session["addtocart"] != null)
{
DataTable dt = new DataTable();
cartQuantity = Convert.ToString(dt.Rows.Count);
}
else
{
cartQuantity = "0";
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
Add2cart Method:
private void add2cart(int id,string lblname,int lblPrice, int lbltotal, int quantitylist, string image)
{
if (Session["addtocart"] != null)
{
DataTable dt = (DataTable)Session["addtocart"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<int>("ID") == id);
if (dataRow.Count() == 0)
{
//lblErrorMessage.Text = "";
DataRow dr = dt.NewRow();
dr["ID"] = id;
dr["Item"] = lblname;
dr["Price"] = lblPrice;
dr["quantity"] = quantitylist;
dr["total"] = lbltotal;
dr["image"] = image;
dt.Rows.Add(dr);
Session["addtocart"] = dt;
cartQuantity= dt.Rows.Count.ToString();
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
else
{
//lblErrorMessage.Text = "Item Already Added!";
}
}
else
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Item", typeof(string));
dt.Columns.Add("Price", typeof(int));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("total", typeof(int));
dt.Columns.Add("image", typeof(string));
DataRow dr = dt.NewRow();
dr["ID"] = id;
dr["Item"] = lblname;
dr["Price"] = lblPrice;
dr["quantity"] = quantitylist;
dr["total"] = lbltotal;
dr["image"] = image;
dt.Rows.Add(dr);
Session["addtocart"] = dt;
cartQuantity=Convert.ToString(dt.Rows.Count);
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
Button Code
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewItem item = (ListViewItem)btn.NamingContainer;
HiddenField hfid = item.FindControl("hfId") as HiddenField;
Label lblitem= item.FindControl("item") as Label;
Label lblPrice = item.FindControl("lblPrice") as Label;
DropDownList lblQuantity = item.FindControl("qtydrpdwn") as DropDownList;
Label lblTotal = item.FindControl("Total") as Label;
HiddenField hfimg = item.FindControl("imgpath") as HiddenField;
add2cart(Convert.ToInt32(hfid.Value),lblitem.Text, Convert.ToInt32(lblPrice.Text), Convert.ToInt32(lblTotal.Text), Convert.ToInt32(lblQuantity.Text),hfimg.Value);
btn.Enabled = false;
//Response.Redirect("index.aspx");
}
The problem is occuring in pageload i think? because session is not recognizing the value coming from add2cart method. it is showing the value in the session of add to cart but not in page load. i cant finding out the problem in the code?
And when i click the button to add to cart. the value remains same 0 not increasing at all?
Try this. I outsourced the update routine in a seperate method which is called each time the button is pressed.
String cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string cartQuantity;
// this will be executed when the page is loaded at the beginning or when refreshed
protected void Page_Load(object sender, EventArgs e)
{
// I don't know what this does, if you also need it for the update
// then put it into the updateQuantity method
if (!IsPostBack)
{
LoadList();
}
// update quantity
updateQuantity();
}
// method to update the quantity
private void updateQuantity()
{
if (Session["addtocart"] != null)
{
DataTable dt = new DataTable();
cartQuantity = Convert.ToString(dt.Rows.Count);
}
else
{
cartQuantity = "0";
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewItem item = (ListViewItem)btn.NamingContainer;
HiddenField hfid = item.FindControl("hfId") as HiddenField;
Label lblitem= item.FindControl("item") as Label;
Label lblPrice = item.FindControl("lblPrice") as Label;
DropDownList lblQuantity = item.FindControl("qtydrpdwn") as DropDownList;
Label lblTotal = item.FindControl("Total") as Label;
HiddenField hfimg = item.FindControl("imgpath") as HiddenField;
add2cart(Convert.ToInt32(hfid.Value),lblitem.Text, Convert.ToInt32(lblPrice.Text), Convert.ToInt32(lblTotal.Text), Convert.ToInt32(lblQuantity.Text),hfimg.Value);
btn.Enabled = false;
//call update method
updateQuantity();
}
Related
I have a dataGridView which contains the check-boxes in its first column. Now as per my requirement i have to get the value of Employee No column for the row whose checkbox has been clicked on another button click event.Also how to get the value for multiple checkbox selected .
Here is my code..
private void btn_load_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
}
Please help me .Thanks in advance..
You can also use the DataSource property:
private void btn_Click(object sender, EventArgs e)
{
int[] employeeIds = (dataGridView1.DataSource as DataTable).Rows
.Cast<DataRow>()
.Where(r => (bool)r["Select"])
.Select(r => Convert.ToInt32(r["Employee No"]))
.ToArray();
}
and use the System.Linq namespace.
Because you have bound your DataTable to the grids DataSource, you could make dt a class variable and use that to check the selected ones.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable dt;
private void btn_load_Click(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
foreach (DataRow row in dt.Rows)
{
if ((bool)row["Select"] == true)
{
}
}
}
}
Suppose to have a global variable in your form class declared as
List<int> empIDs = new List<int> empIDs();
Now in your click event you could write
private void btn_Click(object sender, EventArgs e)
{
empIDs.Clear();
foreach(DataGridViewRow r in dgv.Rows)
{
DataGridViewCheckBoxCell c = r.Cells["Select"] as DataGridViewCheckBoxCell;
if(Convert.ToBoolean(c.Value))
empIDs.Add(Convert.ToInt32(r.Cells["Employee No"].Value));
}
}
At the end of the click event the global variable will be filled with the ID of the employees that have their SELECT cell clicked
i have one dynamic gridview with two link button.if i click that link button event is not firing.but if i call "display" method in page load its working fine.code below
public void display()
{
GridView grdv = new GridView();
grdv.AutoGenerateColumns = false;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
BL.ESSBL bl = new BL.ESSBL();
ds = bl.GetContactList();//getting datatable
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
dt = ds.Tables[0];
grdv.RowDataBound += new GridViewRowEventHandler(grdv_RowDataBound);
grdv.DataSource = null;
grdv.DataBind();
grdv.Columns.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
BoundField boundfield = new BoundField();
boundfield.DataField = dt.Columns[i].ColumnName.ToString();
boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
grdv.Columns.Add(boundfield);
}
TemplateField tmf = new TemplateField();
grdv.Columns.Add(tmf);
tmf = new TemplateField();
grdv.Columns.Add(tmf);
grdv.DataSource = dt;
grdv.DataBind();
pnlupdate.Controls.Add(grdv);
}
}
void grdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int count= e.Row.Cells.Count;
LinkButton lnkupdate= new LinkButton();
lnkupdate.ID = "Update";
lnkupdate.Text = "Update";
LinkButton lnkdelete = new LinkButton();
lnkdelete.ID = "delete";
lnkdelete.Text = "delete";
lnkdelete.Click += new EventHandler(lnkdelete_Click);
lnkupdate.CommandArgument = (e.Row.DataItem as DataRowView).Row[0].ToString();
lnkdelete.CommandArgument = (e.Row.DataItem as DataRowView).Row[0].ToString();
lnkupdate.Click += new EventHandler(lnkupdate_Click);
e.Row.Cells[count-2].Controls.Add(lnkupdate);
e.Row.Cells[count-1].Controls.Add(lnkdelete);
}
}
protected void ddlProcess_SelectedIndexChanged(object sender, EventArgs e)
{
dynamicgridview(); // not working
Clear();
}
void lnkupdate_Click(object sender, EventArgs e)
{
Response.Write(#"<script language=""javascript"">alert(""update details "");</script>");
}
if i put "display" method in page load it will call every postback.i don't want that .i want to call this method in drop down selection changed event. if i put "display" method inside that link click event is not firing.
so what i have to do to overcome this.
You have to create gridview before Page_Load, if you don't bind grid after postback. GridView needs to load ViewState.
private GridView gv;
protected void Page_Init(object sender, EventArgs e)
{
gv = new GridView();
gv.ID = "gv";
gv.AutoGenerateColumns = false;
gv.Columns.Add(new TemplateField());
gv.RowCreated += gv_RowCreated;
gv.RowDataBound += gv_RowDataBound;
pnl.Controls.Add(gv);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gv.DataSource = new object[] {
new object()
};
gv.DataBind();
}
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
var lb = e.Row.FindControl("Update") as LinkButton;
lb.CommandArgument = "1";
}
void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
// If you bind gridview after Page_Init,
// This event will not be fired after postback.
LinkButton lb = new LinkButton();
lb.ID = "Update";
lb.Text = "Update";
lb.Click += lb_Click;
e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(lb);
}
void lb_Click(object sender, EventArgs e)
{
var lb = (LinkButton)sender;
string arg = lb.CommandArgument;
}
Instead of grdv.Columns.Clear(); can u try and see grdv.AutoGenerateColumns = false;. Because i don't thnik there is an error in your code
i want to keep adding data in current row of grid unless i press clear button to change row but when ever i start adding data in new added row it creates a new row . I want to hold previous rows . any help !!!
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null;
ViewState["i"] = ViewState["j"] = 1;
ViewState["state"] = "";
}
}
public static DataTable dt;
public static int i = 1;
protected void txtName_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
if (Convert.ToInt16 (ViewState ["i"]) ==Convert.ToInt16( ViewState["j"]))
{
// here i have to add something
dr = dt.NewRow();
ViewState["state"] = txtName.Text;
dr["RowNumber"] = i;
dr["Column1"] = Convert.ToString(ViewState["state"]) + txtName.Text;
dt.Rows.Add(dr);
}
else if ( Convert .ToInt16 ( ViewState["i"] )!= Convert .ToInt16 ( ViewState["j"]))
{
if (Session["List"] != null)
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtName.Text;
dr["RowNumber"] = i;
ViewState["state"] = txtName.Text;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
}
ViewState["i"] = ViewState["j"];
}
grdData.DataSource = dt;
grdData.DataBind();
}
protected void btnClr_Click(object sender, EventArgs e)
{
ViewState["j"] = i++;
}
}
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null;
ViewState["i"] = ViewState["j"] = 1;
ViewState["state"] = "";
}
}
public static DataTable dt;
public static int i = 1;
protected void txtName_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
if (Session["List"] == null)
{
if (Convert.ToInt16(ViewState["i"]) == Convert.ToInt16(ViewState["j"]))
{
dr = dt.NewRow();
dr["RowNumber"] = i;
dr["Column1"] = Convert.ToString(ViewState["state"]) + txtName.Text;
ViewState["state"] = Convert.ToString(ViewState["state"]) + txtName.Text;
dt.Rows.Add(dr);
}
grdData.DataSource = dt;
grdData.DataBind();
}
if (Session["List"] != null)
{
if ( Convert .ToInt16 ( ViewState["i"] )!= Convert .ToInt16 ( ViewState["j"]))
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtName.Text;
dr["RowNumber"] = i;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
grdData.DataSource = dt;
grdData.DataBind();
}
else if (Convert.ToInt16(ViewState["i"]) == Convert.ToInt16(ViewState["j"]))
{
dt = (DataTable)Session["List"];
ViewState["state"] = grdData.Rows[((grdData.Rows.Count) - 1)].Cells[1].Text;
string i =Convert.ToString( ViewState["state"]);
int j = dt.Rows.Count;
dt.Rows[(dt.Rows.Count)-1]["Column1"] =Convert.ToString(ViewState["state"])+ txtName.Text;
grdData.DataSource = dt;
grdData.DataBind();
}
ViewState["i"] = ViewState["j"];
}
txtName.Text = "";
}
protected void btnClr_Click(object sender, EventArgs e)
{
ViewState["j"] = i++;
ViewState["state"] = "";
// txtName.Text = grdData.Rows[(grdData.Rows.Count - 1)].Cells[1].Text;
}
protected void btnnew_Click(object sender, EventArgs e)
{
dt.Rows[(grdData.Rows.Count - 1)]["Column1"] = txtName.Text;
grdData.DataSource = dt;
grdData.DataBind();
}
}
I generate CheckBoxField in GridView dynamically. but in output the CheckBox is disabled.
How to enable CheckBox dynamically.
I know if add a TemplateField in GridView markup my problem is solved but i won't add TemplateField in GridView
ASPX:
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
Code behind:
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
CheckBoxField chkField = new CheckBoxField();
chkField.DataField = "c1";
chkField.HeaderText = "CheckBox";
chkField.ReadOnly = false;
GridView2.Columns.Add(chkField);
GridView2.DataSource = dTable;
GridView2.DataBind();
I put code in the RowDataBound event to enable the checkbox:
protected void Page_Load(object sender, EventArgs e)
{
this.GridView2.RowDataBound += GridView2_RowDataBound;
BindGrid();
}
void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[0].GetType() == typeof(System.Web.UI.WebControls.DataControlFieldCell))
{
TableCell tc = e.Row.Cells[0];
if (tc.Controls.Count > 0)
{
CheckBox cb = (CheckBox)tc.Controls[0];
if (!(cb == null))
{
cb.Enabled = true;
}
}
}
}
private void BindGrid()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
//CheckBoxField chkField = new CheckBoxField();
//chkField.DataField = "c1";
//chkField.HeaderText = "CheckBox";
//chkField.ReadOnly = false;
//GridView1.Columns.Add(chkField);
GridView2.DataSource = dTable;
GridView2.DataBind();
}
}
Optimize Decker97 answer:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
GridView2.DataSource = dTable;
GridView2.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.Cells[0].Controls[0];
cb.Enabled = true;
}
}
I work several time on this functions but also not working at all.
I populate a gridview by code and I add a button that open a detail of row on click.
I try to add button while populate datatable but not work.
After I try to add button on row_databound method; the button it's rendering but not fire event click.
As follow a semplify code.
I hope that you are able to help me to solve this problem.
Thank's in advance and regards.
P
protected void btnSearch_Click(object sender, EventArgs e)
{
string sSearchQuery = "(" + TextBox1.Text + ")";
loadDynamicGrid(sSearchQuery);
}
private void loadDynamicGrid(string sSearchQuery)
{
//search
.....
var oHitColl = searcher.Search(oParser.Parse(sSearchQuery));
//istance of DataTable
gvResult.Columns.Clear();
gvResult.DataSource = null;
DataTable dt = new DataTable();
DataColumn dcol = new DataColumn("Id", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Table", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Summary", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Link", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Button", typeof(Button));
dt.Columns.Add(dcol);
//Populate la datatable
for (int i = 0; i < oHitColl.Length(); i++)
{
Document oDoc = oHitColl.Doc(i);
DataRow drow = dt.NewRow();
drow["Table"] = oDoc.Get("Table");
drow["Summary"] = oDoc.Get("Summary");
drow["Id"] = oDoc.Get("Id");
string url = ....".aspx";
drow["Link"] = linkText;
//Button btn = CreateButton("dinamicBtn" + i.ToString(), "dinamicBtn" + i.ToString());
//drow["Button"] = btn;
dt.Rows.Add(drow);
}
// add columus in GridView
foreach (DataColumn col in dt.Columns)
{
//Dichiarare i campi bindati e allocare la memoria che serve
BoundField bfield = new BoundField();
bfield.DataField = col.ColumnName;
bfield.HeaderText = col.ColumnName;
gvResult.Columns.Add(bfield);
}
gvResult.DataSource = dt;
gvResult.DataBind();
searcher.Close();
}
protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn = CreateButton("btnOpen_"+ e.Row.RowIndex.ToString(), "Open");
btn.DataBinding +=new EventHandler(btn_DataBinding);
e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(btn);
}
}
private Button CreateButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.Click += new EventHandler(Dynamic_Method);
b.DataBinding += new EventHandler(btn_DataBinding);
return b;
}
private void btn_DataBinding(object sender, EventArgs e)
{
object bound_value_obj = null;
Control ctrl = (Control)sender;
IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;
bound_value_obj = DataBinder.Eval(data_item_container.DataItem,"gvResult.Rows.Count.ToString()");
}
protected void Dynamic_Method(object sender, EventArgs e)
{
Response.Write("You have clicked at: "+DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
}
Any control that you create dynamically need to be re-added at every postback, the events need to be hooked at every postback, etc. In addition to that, you should do this in the OnInit method.