How to enable CheckBoxField in GridView dynamically? - c#

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

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

How to get Value of specific cell of datagridview in Winform application

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

Link button not firing in dynamic gridview in asp.net

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

Morethan one Gridview one Row Databound?

protected void gvMeatDispatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Parent.Parent.ID == "gvMeatDispatch")
{
DataTable dtpartyname = new DataTable();
objRetailPL.status = 4;
dtpartyname = objRetailBAL.GetType(objRetailPL);
DropDownList ddlpn = (DropDownList)e.Row.FindControl("ddlpartyname");
if (ddlpn != null)
{
ddlpn.DataSource = dtpartyname;
ddlpn.DataTextField = "partyname";
ddlpn.DataValueField = "sno";
ddlpn.DataBind();
ddlpn.Items.Add(new ListItem("--Select--", "0"));
ddlpn.SelectedIndex = ddlpn.Items.Count - 1;
}
}
if (e.Row.Parent.Parent.ID== "gvRetail")
{
DataTable dttypeRT = new DataTable();
dttypeRT = objRetailBAL.getretailtype();
DropDownList ddl = (DropDownList)e.Row.FindControl("ddltype");
if (ddl != null)
{
ddl.DataSource = dttypeRT;
ddl.DataTextField = "type";
ddl.DataValueField = "sno";
ddl.DataBind();
ddl.Items.Add(new ListItem("--Select--", "0"));
ddl.SelectedIndex = ddl.Items.Count - 1;
}
}
}
Here "gvMeatDispatch" and "gvRetail" are two gridviews in row databound..my if condition is satisfied but second "gvRetail" is not executed..please help me

Categories

Resources