Gridview Footer Default Value Missing - c#

I have a gridview which can searched by date.
In the gridview, i manually add in footer if the gridview for the date is empty.
It work fine then first load the page.
The problem is :
When load the gridview with data, the footer show default data. After that, select date where no data, default values are missing. If I select another date without data, the default value of footer come out again.
I put breakpoint and it went through the following function, the value is not null but it is no displayed on the Label of footer.
while (Dr.Read())
{
AttendbyFooter.Text = Dr.GetValue(1).ToString();
DepartmentFooter.Text = Dr.GetValue(4).ToString();
}
Gridview databound:
Label AttendbyFooter = GridView1.FooterRow.FindControl("AttendbyFooter") as Label;
//if the footer is null, do nothing. if the footer is not null, continue for other value
if (AttendbyFooter == null)
{
}
else
{
//set default name
AttendbyFooter.Attributes.Add("readonly", "readonly");
Label DepartmentFooter = GridView1.FooterRow.FindControl("DepartmentFooter") as Label;
DepartmentFooter.Attributes.Add("readonly", "readonly");
//create a connection to mssql server
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = ConfigurationManager.ConnectionStrings["CMOSConnectionString"].ConnectionString;
Cn.Open();
//create a command object from the connection
var Cm = Cn.CreateCommand();
//Check database using username(id number)
Cm.CommandText = string.Format(#"Select * From Employee WHERE PassNumber='{0}'", User.Identity.Name);
var Dr = Cm.ExecuteReader();
while (Dr.Read())
{
//Name
AttendbyFooter.Text = Dr.GetValue(1).ToString();
DepartmentFooter.Text = Dr.GetValue(4).ToString();
}
Cn.Close();
}
Generate footer(copy from website)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace YourNamespace
{
public class GridViewExtended : GridView
{
#region Public Properties
[Category("Behavior")]
[Themeable(true)]
[Bindable(BindableSupport.No)]
public bool ShowFooterWhenEmpty
{
get
{
if (this.ViewState["ShowFooterWhenEmpty"] == null)
{
this.ViewState["ShowFooterWhenEmpty"] = false;
}
return (bool)this.ViewState["ShowFooterWhenEmpty"];
}
set
{
this.ViewState["ShowFooterWhenEmpty"] = value;
}
}
#endregion
private GridViewRow _footerRow2;
public override GridViewRow FooterRow
{
get
{
GridViewRow f = base.FooterRow;
if (f != null)
return f;
else
return _footerRow2;
}
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
int rows = base.CreateChildControls(dataSource, dataBinding);
// no data rows created, create empty table if enabled
if (rows == 0 && (this.ShowFooterWhenEmpty))
{
// create the table
Table table = this.CreateChildTable();
DataControlField[] fields;
if (this.AutoGenerateColumns)
{
PagedDataSource source = new PagedDataSource();
source.DataSource = dataSource;
System.Collections.ICollection autoGeneratedColumns = this.CreateColumns(source, true);
fields = new DataControlField[autoGeneratedColumns.Count];
autoGeneratedColumns.CopyTo(fields, 0);
}
else
{
fields = new DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
}
if (this.ShowHeaderWhenEmpty)
{
// create a new header row
GridViewRow headerRow = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
this.InitializeRow(headerRow, fields);
// add the header row to the table
table.Rows.Add(headerRow);
}
// create the empty row
GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = fields.Length;
cell.Width = Unit.Percentage(100);
// respect the precedence order if both EmptyDataTemplate
// and EmptyDataText are both supplied ...
if (this.EmptyDataTemplate != null)
{
this.EmptyDataTemplate.InstantiateIn(cell);
}
else if (!string.IsNullOrEmpty(this.EmptyDataText))
{
cell.Controls.Add(new LiteralControl(EmptyDataText));
}
emptyRow.Cells.Add(cell);
table.Rows.Add(emptyRow);
if (this.ShowFooterWhenEmpty)
{
// create footer row
_footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
this.InitializeRow(_footerRow2, fields);
// add the footer to the table
table.Rows.Add(_footerRow2);
}
this.Controls.Clear();
this.Controls.Add(table);
}
return rows;
}
}
}

Try clearing the date textbox after pageload.

Related

Pass value from boundfield of gridview to controller

I have 2 gridview look like this:
and 2 controller for those gridview:
Gridview Controller 1:
[DataObjectMethod(DataObjectMethodType.Select, false)]
public List<OutstandingOrderInfo> OrderInfo()
{
using (var context = new eToolsContext())
{
var data2 = from po in context.PurchaseOrders
where !po.Closed
select new OutstandingOrderInfo()
{
Order = po.PurchaseOrderID,
Date = po.OrderDate,
VendorName = po.Vendor.VendorName,
ContactPhone = po.Vendor.Phone
};
return data2.ToList();
}
}
GridView2 Controller
[DataObjectMethod(DataObjectMethodType.Select,false)]
public OrderDetail GetOrderDetail (int purchaseOrderID)
{
using (var context = new eToolsContext())
{
var data = from pod in context.PurchaseOrderDetails
where pod.PurchaseOrderID == purchaseOrderID
select new OrderDetail()
{
StockItemID = pod.StockItemID,
Description = pod.StockItem.Description,
QuantityOnOrder = pod.StockItem.QuantityOnOrder,
};
return data.FirstOrDefault();
}
}
I'm trying to pass the value of Order boundfield in Gridview1 to controller of Gridview 2 as the parameter whenever the ViewOrder link button is clicked.
But I received the error that the data I passed is null. What am I doing wrong?
Here is my code for handling the click event:
protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
e.Cancel = true; // to prevent any other processing in the GridView's default Select handling
GridView sendingGridView = sender as GridView; // notice the safe casting
GridViewRow row = sendingGridView.Rows[e.NewSelectedIndex];
var orderID = row.FindControl("Order") as Label;
int puchaseOrderID = int.Parse(orderID.Text);
GetOrderDetail(puchaseOrderID);
}
private void GetOrderDetail(int purchaseOrderID)
{
var controller = new ReceivingController();
var data = controller.GetOrderDetail(purchaseOrderID);
GridView2.DataSource = data.OrderDetail;
GridView2.DataBind();
}

GridView is not binding C#

I am using GridView and trying to bind data to this GridView, but I am facing unusual problem, here is my code :
Method to bind GridView :
private void BindDataSource()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
string queryString6 = "";
string items = "";
if (lb_add_col.Items.Count > 0)
{
foreach (ListItem listItem in lb_add_col.Items)
{
if (listItem.Selected == true)
{
items += listItem.Text + ",";
}
}
}
items = items.TrimEnd(',');
queryString6 = "SELECT "+items+" from " +ddl_tables.Items[0].Text;
System.Data.SqlClient.SqlCommand sqlCmd6 = new System.Data.SqlClient.SqlCommand(queryString6, con);
System.Data.SqlClient.SqlDataAdapter dataAdapter6 = new System.Data.SqlClient.SqlDataAdapter(sqlCmd6);
System.Data.DataSet dataSet6 = new System.Data.DataSet();
dataAdapter6.Fill(dataSet6);
string[] columns = items.Split(',');
for (int i = 0; i < dataSet6.Tables[0].Rows.Count; i++)
{
order.Add(new Orders(columns.Contains("id") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]["id"]) : 0, columns.Contains("name") ? dataSet6.Tables
[0].Rows[i]["name"].ToString() : "N/A", columns.Contains("month") ? dataSet6.Tables[0].Rows[i]["month"].ToString() : "N/A", columns.Contains("effiecency") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]
["effiecency"]) : 0, columns.Contains("latitude") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]["latitude"]) : 0, columns.Contains("longitude") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]
["longitude"]) : 0));
}
this.OrdersGrid.DataSource = order;
this.OrdersGrid.DataBind();
}
From above method order is showing the data but GridView is not binding.
Button Click event on which I am calling this method :
protected void btn_add_col_Click(object sender, EventArgs e)
{
Syncfusion.JavaScript.Models.Column sd;
foreach (ListItem listItem in lb_add_col.Items)
{
if (listItem.Selected == true)
{
sd = new Syncfusion.JavaScript.Models.Column();
if (listItem.Text == "id")
{
sd.IsPrimaryKey = true;
}
sd.Field = listItem.Text;
sd.HeaderText = listItem.Value;
sd.Width = 90;
sd.TextAlign = Syncfusion.JavaScript.TextAlign.Right;
this.OrdersGrid.Columns.Add(sd);
}
}
BindDataSource();
}
If the order contains value after the loop has executed then the data source will be bind to the Grid. But the Grid does not contain the columns that you have defined in the button click, it return all columns in the grid data source. the Grid has only shown the column that you have define in the bindDataSource method,
if dataSet6.Tables[0].Rows.Count is zero, the GridView will databind but there will be no data.

how do i fetch the id of a dynamically created web control

I have been trying to fetch ids of dynamically created dropdownlists(during Page_Load) ,which are in a table, and then find the selected values in those dropdownlists and store these values a table or GridView on button click.This is how i assigned id's(in Page_Load event)
drd.ID = "dbaseid" + rowctr;
drd1id[rowctr]=drd1.ID;
rowctr is the index variable to assign unique id to each dropdown.
How do i fetch the ids from Page_Load . I tried storing the id in an array and then using session variable:
drdid[rowctr]=drd.ID;
drd1id[rowctr]=drd1.ID;
Session["drditem"]=drditem;
Session["drd1item"]=drd1item;
and then tried to fetch the ids in buttonclick event function:
drdid=(string[])Session["drdid"];
drd1id=(string[])Session["drd1id"];
string[] a =new string [50];
for(int i =0;i<noodropdowns;i++)
{
a=drd1id[i];
a.selectedindex//doesnt work !!
}
Is there a way to get the real ids and then work on them ?
I m new to asp.net , My apologies if it sounds noob ish ..
thanks in advance.
Hey if you are trying to loop over all the drop down list in the GridView and get the drop down list ?
//Add the drop down as following in page load
drd.ID = "dbaseid"; //do not add dynamic id other wise you will not able to find it.
//It client id would be different based upon its position in DOM
//loop over gridview row and get the control as following
foreach (GridViewRow row in grid.Rows)
{
var ddl = row.FindControl("dbaseid") as DropDown;
//do what ever with the drop down
}
Found success ,found the dropdowns and saved the selected values in a table .Every time a value from a drop down is selected it is changed in the table as well.Here is the code..
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Collections;
using System.Web.Security;
using System.Text;
using System.Configuration;
using System.Web.SessionState;
using System.Windows;
public partial class Default2 : System.Web.UI.Page
{
Table tblRecipients = new Table();
DropDownList drd = new DropDownList();
DropDownList drd1 = new DropDownList();
protected void Page_Init(object sender, EventArgs e)
{
DataTable dtt = (DataTable)Session["griddata"];
int n = dtt.Columns.Count;
string[] drd1item = new string[n];
string[] excel = new string[n];
for (int i = 0; i < dtt.Columns.Count; i++)
{
excel[i] = dtt.Columns[i].ColumnName;
}
Session["exceldata"] = excel;
////saving sql database column names in an array variable
DataTable dtt1 = (DataTable)Session["dbasecolumns"];
int l = dtt1.Columns.Count;
string[] drditem = new string[l];
string[] sqlcolumn = new string[l];
for (int j = 0; j < dtt1.Columns.Count; j++)
{
sqlcolumn[j] = dtt1.Columns[j].ColumnName;
}
Session["sqlcolumn"] = sqlcolumn;
Session["l"] = l;
//Table Creation
Table mytable = new Table();
mytable.Visible = true;
mytable.GridLines = GridLines.Both;
TableHeaderRow th = new TableHeaderRow();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thc1 = new TableHeaderCell();
mytable.Rows.Add(th);
Label lbl1 = new Label();
Label lbl2 = new Label();
lbl1.Text = "Database";
lbl2.Text = "Excel";
thc.Controls.Add(lbl1);
thc1.Controls.Add(lbl2);
th.Cells.Add(thc);
th.Cells.Add(thc1);
for (int rowctr = 0; rowctr < sqlcolumn.Length; rowctr++)
{
TableCell mycell = new TableCell();
TableCell mycell1 = new TableCell();
for (int cellctr = 0; cellctr < 1; cellctr++)
{
//dropdown with database columns
DropDownList drd = new DropDownList();
drd.Items.Insert(0, new ListItem("--Select--", "0"));
drd.ID = "dbaseid" + rowctr;
for (int i = 0; i < sqlcolumn.Length; i++)
{
drd.Items.Add(sqlcolumn[i]);
drditem[i] = sqlcolumn[i];
}
// drd.SelectedIndexChanged+=new EventHandler(drd1_SelectedIndexChanged);
//dropdown with excel columns
DropDownList drd1 = new DropDownList();
drd1.ID = "excelid" + rowctr;
for (int j = 0; j < excel.Length; j++)
{
drd1.Items.Add(excel[j]);
drd1item[j] = excel[j];
}
// drd1.SelectedIndexChanged +=new EventHandler (drd1_SelectedIndexChanged);
//session variable to store dropdown elements in an array
//Table cells and rows addition
TableRow myrow = new TableRow();
mycell.Controls.Add(drd);
mycell1.Controls.Add(drd1);
myrow.Cells.Add(mycell);
myrow.Cells.Add(mycell1);
mytable.Rows.Add(myrow);
mytable.BorderStyle = BorderStyle.Solid;
}
}
DynamicControlsHolder.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
Table mytable = new Table();
mytable.GridLines = GridLines.Both;
string s;
foreach (Control ctl in DynamicControlsHolder.Controls)
{
if (ctl is Table)
{
Table tblnew = ctl as Table;
{
foreach (Control ctrl in tblnew.Controls)
{
if (ctrl is TableRow)
{
TableRow trow = new TableRow();
TableRow tblrow = ctrl as TableRow;
{
foreach (Control cntrl in tblrow.Controls)
{
if (cntrl is TableCell)
{
TableCell tcell = new TableCell();
TableCell tblcell = cntrl as TableCell;
{
foreach (Control cntrol in tblcell.Controls)
{
if (cntrol is DropDownList)
{
DropDownList myddr = cntrol as DropDownList;
if (cntrol != null)
{
s = myddr.SelectedItem.Text;
tcell.Text = s;
}
}
}
}
trow.Cells.Add(tcell);
}
}
}
mytable.Rows.Add(trow);
}
}
}
}
}
DynamicControlsHolder.Controls.Add(mytable);
}
}
You mentioned that the dynamically created dropdownlists are in a table. I think Anand was referring to that table, not to the GridView you wish to populate with the values of the dropdownlists. So, you could try to loop over the rows of the table and get the dropdownlist ids.

how to set SelectedIndex in DataGridViewComboBoxColumn?

i am using a datagridview in that i am using a datagridviewcomboboxcolumn, comboboxcolumn is displaying text but the problem is i want to select the first item of comboboxcolumn by default how can i do this
DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
i++;
}
The values available in the combobox can be accessed via items property
row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];
the best way to set the value of a datagridViewComboBoxCell is:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as
DataRowView).Row[1].ToString();
}
It worked with me very well
If I had known about doing it in this event, it would have saved me days of digging and
trial and errors trying to get it to set to the correct index inside the CellEnter event.
Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!!
In reviewing all the issues other coders have been experiencing with trying to set
the index inside of a DataGridViewComboBoxCell and also after looking over your code,
all that anyone really needs is:
1. Establish the event method to be used for the "EditingControlShowing" event.
2. Define the method whereby it will:
a. Cast the event control to a ComboBox.
b. set the "SelectedIndex" to the value you want.
In this example I simply set it to "0", but you'd probably want to apply so real life logic here.
Here's the code I used:
private void InitEvents()
{
dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );
}
private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
{
ComboBox ocmb = e.Control as ComboBox;
if ( ocmb != null )
{
ocmb.SelectedIndex = 0;
}
}
If DataGridViewComboBoxCell already exist:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item 1", "0");
dt.Rows.Add("Item 2", "1");
dt.Rows.Add("Item 3", "2");
dt.Rows.Add("Item 4", "3");
for (int i = 0; i < dvg.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
comboCell.DisplayMember = "Item";
comboCell.ValueMember = "Value";
comboCell.DataSource = dt;
};
I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. However, here is what I ended up with:
public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
{
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = dataSource;
if (cbx.Value == null)
{
if(dataSource.Count > 0)
{
T m = (T)cbx.Items[0];
FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
cbx.Value = fi.GetValue(m);
}
}
}
It basically sets the .Display and .ValueMember properties of the DataGridViewComboBoxCell and uses a List as DataSource. It then takes the first item, and uses reflection to get the value of the member that was used as ValueMember and sets the selected value via .Value
Use it like this:
public class Customer
{
private String name;
public String Name
{
get {return this.name; }
set {this.name = value; }
}
private int id;
public int Id
{
get {return this.id; }
set {this.id = value; }
}
}
public class CustomerCbx
{
private String display;
public String Display
{
get {return this.display; }
set {this.display = value; }
}
private Customer value;
public Customer Value
{
get {return this.value; }
set {this.value = value; }
}
}
public class Form{
private void Form_OnLoad(object sender, EventArgs e)
{
//init first row in the dgv
if (this.dgv.RowCount > 0)
{
DataGridViewRow row = this.dgv.Rows[0];
DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];
Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
List<CustomerCbx> custList = new List<CustomerCbx>()
{
new CustomerCbx{ Display = c1.Name, Value = c1},
new CustomerCbx{ Display = c2.Name, Value = c2},
}
InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
}
}
}
}
It seems pretty hacky to me, but I couldn't find any better way so far (that also works with complex objects other than just Strings). Hope that will save the search for some others ;)
You need to set the Items for the new cell. This must be auto done by the column when creating a new row from the UI.
var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});
something different worked for me what i did is to simply set the value of dtataGridComboBox when ever new record is added bu user with 'userAddedRow' event. For the first row I used the code in constructor.
public partial class pt_drug : PatientDatabase1_3._5.basic_templet
{
public pt_drug()
{
InitializeComponent();
dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
}
private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
}
}
Here the solution I have found : select the cell you are interested in so you can cast it to a combobox.
this.Invoke((MethodInvoker)delegate
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
this.dataGridView1.BeginEdit(true);
ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
comboBox.SelectedIndex += 1;
});

Dynamically created LinkButton won't go into command event

I've asked this before, but sadly I'm still having issues and the issue wasn't resolved. Basically, I'm dynamically creating a LinkButton for each row of a table I am generating, and that button has the task of deleting the row with the corresponding ID from the database. To do this, I seemingly need to assign the LinkButton a Command so it'll go into the event when it is clicked. Problem is, when the button's clicked the program never goes into the command - I've put breakpoints in there and it never goes into them. Here's my code:
protected void Page_Init(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
ColorConverter conv = new ColorConverter();
string connection = ConfigurationManager.ConnectionStrings["TPRTestConnectionString"].ConnectionString;
TPRDBDataContext dc = new TPRDBDataContext();
DataContext db = new DataContext(connection);
Table<SageAccount> SageAccount = db.GetTable<SageAccount>();
Table<InvoiceItem> InvoiceItem = db.GetTable<InvoiceItem>();
Table<Invoice> Invoice = db.GetTable<Invoice>();
Boolean alloweditting = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s.alloweditting).Single();
if (alloweditting == false)
{
dtlsInsert.Visible = false;
modalPanel.Visible = false;
}
int sagepk = (from s in dc.Invoices where s.id.ToString() == Request.QueryString["id"] select s.sageaccount).Single();
lblSageID.Text = (from s in dc.SageAccounts where s.ID == sagepk select s.SageID).Single();
lblDate.Text = DateTime.Now.ToShortDateString();
Table table = new Table();
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 += lnkdel_Command;
//lnkdel.Command += new CommandEventHandler(this.lnkdel);
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.Command += lnkdel_Command;
//lnkdel.Command += new CommandEventHandler(this.lnkdel);
lnkdel.CommandArgument = x.id.ToString();
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);
}
else
{
Response.Redirect("Invoices.aspx");
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lnkdel_Command(object sender, CommandEventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["TPRTestConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand comm = new SqlCommand("DELETE FROM InvoiceItem WHERE id = #id", conn);
comm.Parameters.AddWithValue("#id", e.CommandArgument.ToString());
conn.Open();
try
{
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
Note I've commented out 2 of the crucial lines for posting here, just to point out that I've tried both of the lines that's commented out, and neither work :(
You need to add the controls on every postback. You appear to be only creating them on the initial get (that query string check). On the post back, those controls never get recreated so no event fires.
It's notoriously counter-intuitive, but while ASP.NET bends over backwards to make you think that the instance of your page class is the same between two HTTP requests, the reality is that they are not the same. A new instance is created each time. It looks like you are trying to avoid adding the dynamically generated controls multiple times -- thinking you don't want duplicates. The reality is that you will never get duplicates when adding dynamically generated controls in a life-cycle method such as OnInit() since it's always a new instance of the page class, and thus those dynamically generated controls are gone.
The reason this is usually transparent to developers is that all the controls in the code-front are automatically re-generated for you on both the initial request and every single post-back. For your dynamically created controls, you happen to have this line:
if (Request.QueryString["id"] != null) { ... }
Unless you're doing something special, that "id" attribute will not be in the query string on the postback. This means that none of the code in the if block will be run on the post back (when your event actually fires.) This means that your if-check at the top should be removed altogether. All that code should run for each and every request (GET and POST).
Just saying I've created a workaround - simply creating a simple link to the page, along with a query string containing the id of the row to delete

Categories