I have a button which is created from a MySQL query result. It looks like this:
1 Product name |add to basket|
And when I press the "add to basket" button, the product appears in a table on the right side(basket). Like this:
1 Product name |remove|
But for some reason, the remove button click-event removes all items from basket. When I press add to basket again, all items appear in the basket again.
This is whole class. Thank you for your help
public partial class neworder : System.Web.UI.Page
{
Basket basket;
Table BasketTable;
private int countRows = 0;
private string distance;
private string categories;
ArrayList categoryList = new ArrayList();
ArrayList productList = new ArrayList();
private string products = "";
public string Products
{
get { return products; }
set { products = value; }
}
public string Categories
{
get { return categories; }
set { categories = value; }
}
public string Distance
{
get { return distance; }
set { distance = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
basket = new Basket();
Session["basket"] = basket;
}
populateCategories();
populateProducts();
loadBasket(); // if this is comment then i items are added fine
//to basket but cant be remove, if its not commented then i can add
//only 2 items in basket
}
private void populateCategories()
{
using (MySqlConnection cn = new MySqlConnection(Static.MysqlServer1))
{
cn.Open();
String strSQL = "SELECT category_name FROM categories;";
MySqlCommand cmdPLT = new MySqlCommand(strSQL, cn);
MySqlDataReader myReader;
myReader = cmdPLT.ExecuteReader();
while (myReader.Read())
{
string cat = myReader.GetString(0);
categoryList.Add(cat);
categories += "" + cat + "<br />";
}
}
}
private void populateProducts()
{
Panel1.Controls.Clear();
string tem = "";
foreach (string s in categoryList)
{
Table tableTitle = new Table();
TableRow row1 = new TableRow();
tableTitle.ID = s + "Title";
tableTitle.CssClass = "rest2";
Panel1.Controls.Add(tableTitle);
TableCell cell2 = new TableCell();
Label label2 = new Label();
label2.Text = "<a name="+s+">"+s+"</a>";
label2.ID = "TitleText_" + s;
cell2.Controls.Add(label2);
row1.Cells.Add(cell2);
tableTitle.Controls.Add(row1);
Table table = new Table();
table.ID = s;
table.CssClass = "rest";
Panel1.Controls.Add(table);
using (MySqlConnection cn = new MySqlConnection(Static.MysqlServer1))
{
string name = "";
string size = "";
int id = -1;
double price = 0.0;
cn.Open();
String strSQL = "SELECT product_id, product_name, product_price, product_size FROM products join categories on categories.CATEGORY_ID = products.CATEGORY_ID where category_name ='" + s + "' order by product_order asc;";
MySqlCommand cmdPLT = new MySqlCommand(strSQL, cn);
MySqlDataReader myReader;
myReader = cmdPLT.ExecuteReader();
while (myReader.Read())
{
name = (string)myReader["product_name"];
id = (int)myReader["product_id"];
size = (string)myReader["product_size"];
price = (double)myReader["product_price"];
productList.Add(new Products(id, name, size, price));
GenerateRow(s, name, size, price, table, id);
}
if (!tem.Equals(""))
{
tem += "</table>";
}
}
products += tem;
tem = "";
}
}
private void GenerateRow(string category, string name, string size, double price, Table table,int id )
{
TableRow row1 = new TableRow();
//ROW 1 NAME
TableCell cell1 = new TableCell();
Label label1 = new Label();
label1.Text = name;
cell1.Style.Add("width", "300px !important");
label1.ID = "NameText_" + category+id;
cell1.Controls.Add(label1);
row1.Cells.Add(cell1);
//ROW 2 Size
TableCell cell2 = new TableCell();
Label label2 = new Label();
cell2.Style.Add("width", "100px !important");
label2.Text = size;
label2.ID = "SizeText_" +category+ id;
cell2.Controls.Add(label2);
row1.Cells.Add(cell2);
//ROW 1 PRICE
TableCell cell3 = new TableCell();
Label label3 = new Label();
cell3.Style.Add("width", "60px !important");
label3.Text = "" + price;
label3.ID = "Price_" + category + id;
cell3.Controls.Add(label3);
row1.Cells.Add(cell3);
//ROW 1 BUTTON
TableCell cell4 = new TableCell();
cell4.Style.Add("height", "25px !important");
Button button = new Button();
button.Text = "+";
button.Click += button_Click;
button.ID = ""+id;
cell4.Controls.Add(button);
row1.Cells.Add(cell4);
table.Controls.Add(row1);
}
private void loadBasket()
{
Basket temp = (Basket)Session["basket"];
BasketTable = new Table();
BasketTable.ID = "basket";
BasketTable.CssClass = "rest";
PanelBasket.Controls.Clear();
PanelBasket.Controls.Add(BasketTable);
foreach (Products p in temp.ProductList)
{
TableRow row1 = new TableRow();
//ROW 1 NAME
TableCell cell1 = new TableCell();
Label label1 = new Label();
label1.Text = p.Name;
cell1.Style.Add("width", "100px !important");
label1.ID = p.Name;
cell1.Controls.Add(label1);
row1.Cells.Add(cell1);
//ROW 2 Size
TableCell cell2 = new TableCell();
Label label2 = new Label();
cell2.Style.Add("width", "40px !important");
label2.Text = p.Size;
label2.ID = p.Size;
cell2.Controls.Add(label2);
row1.Cells.Add(cell2);
//ROW 1 PRICE
TableCell cell3 = new TableCell();
Label label3 = new Label();
cell3.Style.Add("width", "60px !important");
label3.Text = p.Price+"";
label3.ID = p.Price + "";
cell3.Controls.Add(label3);
row1.Cells.Add(cell3);
//ROW 1 BUTTON
TableCell cell4 = new TableCell();
cell4.Style.Add("height", "25px !important");
Button remove = new Button();
remove.Text = "-";
remove.Click += new EventHandler(button99_Click);
remove.ID = "remove" + p.Id;
cell4.Controls.Add(remove);
row1.Cells.Add(cell4);
BasketTable.Controls.Add(row1);
}
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
string buttonId = button.ID;
foreach (Products p in productList)
{
if (p.Id == Convert.ToInt32(buttonId))
{
Basket temp = (Basket)Session["basket"];
temp.addPruduct(p);
Session["basket"] = temp;
loadBasket();
Label1.Text = temp.ProductList.Count + "";
}
}
}
protected void remove_Click(object sender, EventArgs e)
{
Label1.Text = "test";
}
}
Related
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";
I have table and each row contains a button. If I click the button, I want to retrieve the value from the first column in that particular row. This is my code, how can I do that. Thank you
foreach (var c in list)
{
TableRow row = new TableRow();
TableCell c0 = new TableCell();
c0.Text = string.Format("<img src='"+c.Movie_poster+ "'/>");
TableCell c1 = new TableCell();
c1.Text = c.Name;
TableCell c2 = new TableCell();
c2.Text = c.Date.ToStirng();
TableCell c3 = new TableCell();
c3.Text = c.desc;
TableCell c4 = new TableCell();
c4.Text = c.genre;
TableCell c5 = new TableCell();
//Add each string to cell in row
row.Cells.Add(c0);
row.Cells.Add(c1);
row.Cells.Add(c2);
row.Cells.Add(c3);
row.Cells.Add(c4);
row.Cells.Add(c5);
//Add the row to the table
Table.Rows.Add(row);
Button getname = new Button();
getname.Text = "Reserve";
getname.Click+= new EventHandler(getname_Click);
c5.Controls.Add(getname);
}
}
protected void reserve_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
TableRow row = (TableRow)btn.
string name = row.Cells[1].Text;
lbl.Text = name;
}
Before create button you should write a new attribute with Row number.
//Add the row to the table
Table.Rows.Add(row);
Button getname = new Button();
getname.Attributes.Add("idRow", idrow);
idrow += 1;
getname.Text = "Reserve";
getname.Click += new EventHandler(getname_Click);
Then in you reserve_Click you should get the row with the ID stored in button attributes
Button btn = (Button)sender;
int idRow = int.Parse(btn.Attributes["id"]);
TableRow row = t.Rows[idRow];
You can bind the value of the Column to the Button as a CommandArgument.
Button getname = new Button();
getname.Text = "Reserve";
getname.CommandName = "Reserve";
getname.CommandArgument = "Column Value";
getname.Command += new CommandEventHandler(Button1_Command);
And then in the Button Command
protected void Button1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Reserve")
{
string columnValue = e.CommandArgument.ToString();
}
}
I have a gridview which is populated at runtime with a table with unknow number of columns which are not known before hand.
I want to apply column filtering on all columns with Drop Down List.
How can I achieve it. Using Jquery, Linq or simple C sharp Coding.
public partial class DetailView : System.Web.UI.Page
{
public static int y = 0;
public static String colName = "";
public static Boolean flag = false;
static String folder = "";
static public MySqlConnection conn = null;
static public DropDownList dp = null;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strcon = ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
conn = new MySqlConnection(strcon);
conn.Open();
Response.Write(Session["cols"].ToString());
Response.Write(Session["id"].ToString());
// Response.Write("qw");
folder = Session["folderName"].ToString();
colName = Session["cols"].ToString();
GridBind(folder, colName, flag);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void GridBind(String folder, String colName, Boolean val)
{
GridView1.DataSource = null;
GridView1.DataBind();
GridView1.Columns.Clear();
y = 0;
MySqlDataAdapter da;
if (val == false)
{
da = new MySqlDataAdapter("select * from " + folder + "", conn);
}
else
{
da = new MySqlDataAdapter("select * from " + folder + " where abc= '" + colName + "'", conn);
}
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("emp"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Add(linkF);
}
else if (coloumn.ColumnName.Equals("emp"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Add(bfield);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa, String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "", conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
dp.EnableViewState = true;
// DetailView.dp.ID = y.ToString();
y++;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
// DetailView.dp.ID = DetailView.y.ToString();
// Response.Write(_Default.dp.ID);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DataTable a = new DataTable();
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
// String ID = list.ID.ToString();
// Session["id"] = ID;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
// Response.Write(DetailView.colName);
GridBind(fold, DetailView.colName, true);
}
}
}
When i am calling GridBind function from event handler it is giving Null pointer Excpetion at GridView1.DataSource = null;
My GridView1 is present in DetailView.aspx
}
Any help be highly appreciated
Thanks
A coworker and I can't figure out why the EventHandlers in the following code aren't getting fired. The function is called twice before the first page loads, and AutoPostBack is set to true. The lnkbtn button and the ddlDose DropDownList are the ones not being fired. It posts back, but it doesn't call the event handler. Here's some code...can anybody see anything inherently wrong?
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
tblMedOrdering = (Table)Session["tblMedOrdering"];
List<string>medNames = (List<string>)Session["medNamesList"];
populateMeds(medNames);
}
}
PopulateMeds:
protected void populateMeds(List<string> medNames)
{
if (medNames.Count == 0)
{
tblMedOrdering = (Table)Session["tblMedOrdering"];
}
else
{
DataSet ds = new DataSet();
string strConn = Application["dbconn"].ToString();
using (SqlConnection dbconn = new SqlConnection(strConn))
using (SqlCommand medDbcmd = dbconn.CreateCommand())
{
dbconn.Open();
for (int i = 0; i < medNames.Count; i++)
{
DropDownList ddlDose = new DropDownList();
DropDownList ddlSig = new DropDownList();
int flag = 0;
if ((Table)Session["tblMedOrdering"] != null)
{
for (int j = 0; j < tblMedOrdering.Rows.Count; j++)
{
if (tblMedOrdering.Rows[j].Cells[3].Text == medNames[i].ToString())
{
flag = 1;
ddlSig = (DropDownList)tblMedOrdering.Rows[i].Cells[2].FindControl(medNames[i].ToString() + "ddlSig");
if (ddlSig == null)
{
ddlSig.ID = medNames[i].ToString() + "ddlSig";
ListItem liDefaultSig = new ListItem();
liDefaultSig.Value = "0";
liDefaultSig.Text = "Select . . .";
ddlSig.Items.Add(liDefaultSig);
}
break;
}
}
}
if (flag != 1)
{
ListItem liDefault = new ListItem();
liDefault.Value = "0";
liDefault.Text = "Select . . .";
ddlDose.Items.Add(liDefault);
ddlSig.Items.Add(liDefault);
ddlDose.ID = medNames[i].ToString() + "ddlDose";
ddlSig.ID = medNames[i].ToString() + "ddlSig";
ddlDose.AutoPostBack = true;
ddlDose.TextChanged += new EventHandler(ddlDose_SelectedIndexChanged);
medDbcmd.CommandText = "Select distinct medorderid, dose from ordertablemeds where medordername = '" + medNames[i].ToString() + "'";
SqlDataReader dr = medDbcmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
ListItem liDose = new ListItem();
liDose.Value = dr["medorderid"].ToString();
liDose.Text = dr["dose"].ToString();
ddlDose.Items.Add(liDose);
}
dr.Close();
}
TableRow tr = new TableRow();
tr.ID = medNames[i].ToString() + "TableRow";
TableCell tcDose = new TableCell();
TableCell tcSig = new TableCell();
TableCell tcRemove = new TableCell();
TableCell tcMedName = new TableCell();
tcDose.Controls.Add(ddlDose);
tcSig.Controls.Add(ddlSig);
tcMedName.Text = medNames[i].ToString();
tcMedName.ID = medNames[i].ToString() + "medname";
LinkButton lnkbtn = new LinkButton();
lnkbtn.Text = "X";
lnkbtn.ForeColor = System.Drawing.Color.Red;
lnkbtn.ID = medNames[i].ToString() + "_lnkbtn" + tblMedOrdering.Rows.Count;
lnkbtn.Click += new EventHandler(Reset_Click);
tcRemove.Controls.Add(lnkbtn);
tr.Cells.Add(tcRemove);
tr.Cells.Add(tcDose);
tr.Cells.Add(tcSig);
tr.Cells.Add(tcMedName);
tblMedOrdering.Rows.Add(tr);
}
}
tblMedOrdering.DataBind();
dbconn.Close();
}
}
Session["tblMedOrdering"] = tblMedOrdering;
if (medNames.Count == 0)
{
cpeMeds.Collapsed = true;
cpeMeds.ClientState = "True";
}
List<string> medNamesList = new List<string>();
DropDownList ddl = new DropDownList();
for (int k = 0; k < tblMedOrdering.Rows.Count; k++)
{
ddl = (DropDownList)tblMedOrdering.Rows[k].Cells[1].FindControl(tblMedOrdering.Rows[k].Cells[3].Text +"ddlDose");
ddl.SelectedIndexChanged += new EventHandler(ddlDose_SelectedIndexChanged);
medNamesList.Add(tblMedOrdering.Rows[k].Cells[3].Text);
}
Session["medNamesList"] = medNamesList;
}
PopulateMeds is just a function that gets called in the code-behind and is given a list of string names, so it doesn't need args as if it were a control (objects sender, EventArgs e).
Move that logic to OnInit and the event handlers should function properly, assuming that everything else is correct. I would also check to make sure that you don't have validation interfering with the postback.
For every row in my 'table' I am manually creating, there must be a LinkButton to delete a database row that matches a column in the table. Because no 2 controls can have the same name, I've had to use a GUID to name them so they're all unique.
Problem is, right now when I click Delete, the page posts back with no changes, but I've been told that I need to recreate the controls - but how do I recreate them in Page_Load when their ID's are randomly generated? Here's my code:
Table table = new Table();
table.GridLines = GridLines.None;
//table.BorderWidth = 1;
//table.BorderColor = (System.Drawing.Color)conv.ConvertFromString("black");
table.Width = Unit.Percentage(100);
table.GridLines = (GridLines)3;
TableHeaderRow header = new TableHeaderRow();
header.BackColor = (System.Drawing.Color)conv.ConvertFromString("#EDEDED");
foreach (string header2 in new string[] {"", "Quantity", "Rate", "Description", "Nominal Code", "Subtotal" })
{
TableCell cell = new TableCell();
cell.Text = header2;
header.Cells.Add(cell);
}
table.Rows.Add(header);
var data = (from s in dc.InvoiceItems where s.invoiceid.ToString() == Request.QueryString["id"].ToString() select s);
foreach (var x in data)
{
TableRow row = new TableRow();
if (x.invoicetext == null)
{
decimal total;
try
{
total = (decimal)x.rate * (decimal)x.quantity;
}
catch
{
total = 0;
}
int i = 0;
foreach (string columnData in new string[] {x.id.ToString(), x.quantity.ToString(), x.rate.ToString(), x.description, x.nominalcode, total.ToString("N2") })
{
TableCell cell = new TableCell();
{
if (i == 0)
{
LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.ID = "lnkDel" + Guid.NewGuid();
if (alloweditting == false)
{
lnkdel.Enabled = false;
}
lnkdel.Font.Bold = false;
lnkdel.CommandArgument = x.id.ToString();
lnkdel.Command += (s, e2) =>
{
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand comm = new SqlCommand("DELETE FROM InvoiceItem WHERE id = #id", conn);
comm.Parameters.AddWithValue("#id", e2.CommandArgument);
conn.Open();
try
{
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
};
cell.Controls.Add(lnkdel);
i++;
}
else
{
cell.Text = columnData;
}
}
row.Cells.Add(cell);
}
runningtotal = runningtotal + total;
}
else
{
int i = 0;
foreach (string columnData in new string[] {x.id.ToString(), x.invoicetext })
{
TableCell cell = new TableCell();
if (i == 0)
{
LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.ID = "lnkDel" + Guid.NewGuid();
if (alloweditting == false)
{
lnkdel.Enabled = false;
}
lnkdel.Font.Bold = false;
lnkdel.CommandArgument = x.id.ToString();
rowid = lnkdel.CommandArgument;
lnkdel.Command += (s, e2) =>
{
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand comm = new SqlCommand("DELETE FROM InvoiceItem WHERE id = #id", conn);
comm.Parameters.AddWithValue("#id", rowid);
conn.Open();
try
{
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
};
cell.Controls.Add(lnkdel);
i++;
}
else
{
cell.Text = columnData;
cell.ColumnSpan = 5;
}
row.Cells.Add(cell);
}
}
switch (x.formatoptions)
{
case 1:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("black");
row.Font.Bold = false;
break;
case 2:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("black");
row.Font.Bold = true;
break;
case 3:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("red");
row.Font.Bold = false;
break;
case 4:
row.ForeColor = (System.Drawing.Color)conv.ConvertFromString("red");
row.Font.Bold = true;
break;
}
table.Rows.Add(row);
}
TableFooterRow row2 = new TableFooterRow();
TableCell cell2 = new TableCell();
cell2.Text = "<span style\"text-align: right; width: 100%;\">Total = <b>" + runningtotal.ToString("N2") + "</b></span>";
cell2.ColumnSpan = 6;
row2.Cells.Add(cell2);
table.Rows.Add(row2);
var update = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s).Single();
update.total = runningtotal;
dc.SubmitChanges();
datatable.Controls.Clear();
datatable.Controls.Add(table);
}
Don't use a GUID. Make the ID value from the rowid, so it's a repeatable value like "row_784".
For example, instead of
lnkdel.ID = "lnkDel" + Guid.NewGuid();
use
lnkdel.ID = "lnkDel" + x.id.ToString();
You need to create them in Page_Init, not Page_Load. You should only need to move the call to the code that creates your table to Page_Init, and everything should work as you expect.