Link button not firing in dynamic gridview in asp.net - c#

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

Related

When I click on the LinkButton, it doesn't call the function "LinkButton_Click"

The LinkButton I need to do it on backend, so I unable to use the OnClientClick at frontend. Any idea how to solve it?
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Staff ID";
e.Row.Cells[1].Text = "Staff Name";
e.Row.Cells[2].Text = "Position";
e.Row.Cells[3].Text = "Status";
e.Row.Cells[4].Text = "Phone";
e.Row.Cells[5].Text = "Email";
//Add an addition column, else cant add linkbutton at the last column
e.Row.Controls.Add(tc);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
//add linkbutton at every last column
e.Row.Controls.Add(tc);
LinkButton link = new LinkButton();
link.ID = "lbEdit";
link.Text = "Edit";
e.Row.Cells[6].Controls.Add(link);
link.Click += new EventHandler(LinkButton_Click);
if (e.Row.Cells[3].Text == "Inactive")
{
e.Row.Cells[3].CssClass = "redCell";
}
}
}
This is the LinkButton_Click function
protected void LinkButton_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('It works!')</script>");
Response.Redirect("~/product.aspx");
}
or where can I paste my "link.Click += new EventHandler(LinkButton_Click);"?
This is the <asp:GridView />
<asp:GridView CssClass="GridView" ID="staffList" AutoGenerateColumns="true" runat="server" onrowdatabound="GridView_RowDataBound">
</asp:GridView>
The entire backend code
public partial class staff : System.Web.UI.Page
{
string sqlConn = Convert.ToString(ConfigurationManager.AppSettings["connectionString"]);
//LinkButton link = new LinkButton();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT * from Staff";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
staffList.DataSource = dt;
staffList.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
LinkButton link = new LinkButton();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Staff ID";
e.Row.Cells[1].Text = "Staff Name";
e.Row.Cells[2].Text = "Position";
e.Row.Cells[3].Text = "Status";
e.Row.Cells[4].Text = "Phone";
e.Row.Cells[5].Text = "Email";
//Add an addition column, else cant add linkbutton at the last column
e.Row.Controls.Add(tc);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
//add linkbutton at every last column
e.Row.Controls.Add(tc);
link.ID = "lbEdit";
link.Text = "Edit";
e.Row.Cells[6].Controls.Add(link);
link.Click += new EventHandler(LinkButton_Click);
//maybe can create a for loop at here to store all data
if (e.Row.Cells[3].Text == "Inactive")
{
e.Row.Cells[3].CssClass = "redCell";
}
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('It works!')</script>");
Response.Redirect("~/product.aspx");
}
}
When you click the button, a PostBack occurs and Gridview binding will be lost and as well as the buttons links. The following saves the gridView.DataSource into session. Note the if (!IsPostPack) is removed:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["gvDS"] != null)
{
GridView1.DataSource = Session["gvDS"];
GridView1.DataBind();
}
else
BindGridView();
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT * from Staff";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
staffList.DataSource = dt;
staffList.DataBind();
Session["gvDS"] = GridView1.DataSource; // save into session
}

My Cart Label Value is not increasing in masterpage?

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();
}

DropDownList inside Gridview selectedindexchanged not firing on default selected item during dropdown bind

I have a Gridview with dropdownlist is created dynamically in OnRowDataBound event of gridview, initially I am setting a selected value.
The problem is when I switch to different index of dropdown its working fine but when I change to the default selected index the SelectedIndexChanged is not fired.
Kindly help me..
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList DropDownList1 = new DropDownList();
DropDownList1.ID = "DropDownList1";
DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
DropDownList1.EnableViewState = true;
DropDownList1.AutoPostBack = true;
DropDownList1.EnableViewState = true;
string sql1 = ".....";
DataTable dtDDL = new DataTable();
dtDDL = SQL.ReturnDataTable(sql1);
if (dtDDL.Rows.Count > 0)
{
DropDownList1.DataSource = dtDDL;
DropDownList1.DataTextField = "CODE";
DropDownList1.DataValueField = "CODE";
DropDownList1.DataBind();
DropDownList1.Font.Size = 8;
//DropDownList1.Items.Insert(0, new ListItem("0", "0"));
}
DropDownList1.SelectedValue = dtShift.Rows[0]["SHIFT_CODE"].ToString();
DropDownList1.ToolTip = dtShift.Rows[0]["ShiftTime"].ToString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//not coming here for default index changed
}

How to enable CheckBoxField in GridView dynamically?

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;
}
}

add button in a gridview dynamically populate: event click not fire

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.

Categories

Resources