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

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.

Related

Unable to Find Control in RowEditing event for TemplateFields in GridView

I am adding columns to gridview from codebehind.
For boundfields, i am able to find control and textbox value while updating the row.
But for template fields, i am not able to get controls to the code behind, so i am unable to get the textbox value.
Can please suggest how to get textbox value in codebehind for template fields
My Code
protected void gvbind()
{
conn.Open();
string Query = "SELECT * FROM testactiondatabase_db.actions";
MySqlCommand MyCommand2 = new MySqlCommand(Query, conn);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dt = new DataTable();
MyAdapter.Fill(dt);
TaskGridView.Columns.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName.ToString().ToUpper().Contains("DATE"))
{
TemplateField bfield = new TemplateField();
bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dt.Columns[i].ColumnName.ToString());
bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, dt.Columns[i].ColumnName.ToString());
bfield.EditItemTemplate = new GridViewTemplate(ListItemType.EditItem, dt.Columns[i].ColumnName.ToString());
TaskGridView.Columns.Add(bfield);
}
else
{
BoundField boundfield = new BoundField();
boundfield.DataField = dt.Columns[i].ColumnName.ToString();
boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
TaskGridView.Columns.Add(boundfield);
}
}
TaskGridView.DataSource = dt;
TaskGridView.DataBind();
TaskGridView.Width = 600;
TaskGridView.HeaderStyle.CssClass = "header";
TaskGridView.RowStyle.CssClass = "rowstyle";
conn.Close();
}
public class GridViewTemplate : ITemplate
{
ListItemType _templateType;
string _columnName;
public GridViewTemplate(ListItemType type, string colname)
{
_templateType = type;
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
Label lbl = new Label();
lbl.Text = _columnName;
container.Controls.Add(lbl);
break;
case ListItemType.Item:
Label lb1 = new Label();
lb1.DataBinding += new EventHandler(lb1_DataBinding);
container.Controls.Add(lb1);
break;
case ListItemType.EditItem:
TextBox tb1 = new TextBox();
tb1.ID = _columnName;
tb1.DataBinding += new EventHandler(tb1_DataBinding);
tb1.Attributes.Add("class", "myDatePickerClass");
container.Controls.Add(tb1);
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = Convert.ToDateTime(dataValue.ToString()).ToString("dd/MM/yyyy");
}
}
void lb1_DataBinding(object sender, EventArgs e)
{
Label txtdata = (Label)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = Convert.ToDateTime(dataValue.ToString()).ToString("dd/MM/yyyy");
}
}
}
I am using the following code for reading the template field textbox value while updating the row but the controls are 0 for the cell.
GridViewRow row = (GridViewRow)TaskGridView.Rows[e.RowIndex];
TextBox textnew = (TextBox)row.Cells[j].Controls[0];
Try using FindControl.
TextBox textnew = TaskGridView.Rows[e.RowIndex].FindControl(_columnName) as TextBox;
But if I use your snippet like this, with setting an EditIndex manually, it also works... The value of te TextBox is Cell 1 is changed.
TaskGridView.EditIndex = 1;
TaskGridView.DataSource = dt;
TaskGridView.DataBind();
TaskGridView.Width = 600;
TaskGridView.HeaderStyle.CssClass = "header";
TaskGridView.RowStyle.CssClass = "rowstyle";
GridViewRow row = (GridViewRow)TaskGridView.Rows[TaskGridView.EditIndex];
TextBox textnew = (TextBox)row.Cells[1].Controls[0];
textnew.Text = "test";

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

databind a gridview populated in the code behind

I have tried a lot and have reached a dead end.
I have a to show multiple gridviews on one page and all these are getting populated dynamically.
i have figured a way to populate the gridview dynamically and display them, but i cannot get how to modify these values and display them as i want.
here is the code. for .aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:Panel ID="Panel1" runat="server" ScrollBars ="Auto" Height="500px" BorderColor="#003399" BorderWidth="3px">
</asp:Panel>
</asp:Content>
and here is the code for .aspx.cs
for (int j = 0; j < 5; j++)
{
GridView Grid = new GridView();
ArrayList machID = new ArrayList();
ArrayList machName = new ArrayList();
Grid.ID = machGrps[j].ToString();
Grid.AllowSorting = true;
Grid.CellSpacing = 2;
Grid.GridLines = GridLines.None;
Grid.Width = Unit.Percentage(100);
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(Session["ConnectionStringSQL"].ToString());
connection.Open();
SqlCommand sqlCmd = new SqlCommand("select MachineID, MachineName from Machines", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
connection.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
machID.Add(dt.Rows[i]["MachineID"].ToString());
machName.Add(dt.Rows[i]["MachineName"].ToString());
}
DataTable taskTable = new DataTable();
taskTable.Columns.Add("MachineID");
taskTable.Columns.Add("MachineName");
if (machID.Count != 0)
{
for (int i = 0; i < machID.Count; i++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["MachineID"] = machID[i];
tableRow["MachineName"] = machName[i];
taskTable.Rows.Add(tableRow);
}
}
Session["TaskTable"] = taskTable;
Grid.DataSource = Session["TaskTable"];
Grid.DataBind();
Label label = new Label();
label.Text = "Machine Grp" + Grid.ID;
Panel1.Controls.Add(label);
Panel1.Controls.Add(Grid);
}
}
NOTE THIS CODE BELOW CANNOT BE DONE ANYMORE AS I POPULATE THE GRIDVIEW DIRECTLY FROM THE TABLES:
I used to modify like this when the ondatabound="GridView1_DataBound" if is called from the .aspx page
the databound code looks like this:
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow myRow in GridView1.Rows)
{
//this is where ID is stored in an label template
Label Label3 = (Label)myRow.FindControl("Label3");
int val = Convert.ToInt32(Label3.Text);
Image Image5 = (Image)myRow.FindControl("Image5");
if (Convert.ToInt32(Label3.Text) < 0)
{
Image5.ImageUrl = "~/NewFolder1/warning_16x16.gif";
}
else
{
Image5.ImageUrl = "~/NewFolder1/1258341827_tick.png";
}
}
}
Two things:
protected void GridView1_DataBound(object sender, EventArgs e) {
foreach (GridViewRow myRow in GridView1.Rows) {
// blah blah blah code goes here
}
}
should be
//now e is a
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
// blah blah blah, this lets you work on one row at a time.
// since the framework does this per row, you don't need to parse the gridview
// yourself, altho you're more than welcome to.
// But you can get more control this way. I promise.
Label Label3 = (Label)e.Row.FindControl("Label3");
int val = Convert.ToInt32(Label3.Text);
Image Image5 = (Image)e.Row.FindControl("Image5");
if (val < 0)
{
Image5.ImageUrl = "~/NewFolder1/warning_16x16.gif";
}
else
{
Image5.ImageUrl = "~/NewFolder1/1258341827_tick.png";
}
// alternately write the code above like this:
Image Image5 = (Image)e.Row.FindControl("Image5");
Image5.ImageUrl = (val < 0) ? "~/NewFolder1/warning_16x16.gif" : "~/NewFolder1/1258341827_tick.png";
// that's called the ternary operator. Takes up less space, does the same thing.
}
}
Please don't ignore this part
Now to the other part, are you aware that you can still bind in the backside like thus:
GridView1.RowDataBound += GridView1_RowDataBound;
Put it here:
for (int j = 0; j < 5; j++)
{
GridView Grid = new GridView();
ArrayList machID = new ArrayList();
ArrayList machName = new ArrayList();
//NEW LINE (doesn't need the comment or the blank space tho)
Grid.RowDataBound += Grid_RowDataBound;
Grid.ID = machGrps[j].ToString();
Grid.AllowSorting = true;
Grid.CellSpacing = 2;
Grid.GridLines = GridLines.None;
Grid.Width = Unit.Percentage(100);
Do your dynamic edits on GridView1_RowDataBound not on GridView1_DataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label Label3 = (Label)e.Row.FindControl("Label3");
....
}
}
Is it blowing up when you're binding the DataSource to the Session object?
Grid.DataSource = taskTable;

Categories

Resources