Holding dynamic Controls on postback not working - c#

I get this error and do not find the problem:
Object reference not set to an instance of an object.
My Code:
Page Init:
else if (Request.QueryString["CompanyID"] != null)
{
pnlComp.Visible = true;
if (Convert.ToString(ViewState["Generated"]) != "true")
{
createCompSite();
ViewState["Generated"] = "true";
}
}
Page Load:
Verification.Check();
if (!IsPostBack)
{
sFilter= null;
FillGridviewAndValues();
}
if (Convert.ToString(ViewState["Generated"]) == "true")
createCompSite();
Function:
TableHeaderRow tHRow = new TableHeaderRow();
TableHeaderCell tHeader = new TableHeaderCell();
tHeader.Text = dr.Field<string>("Loc");
tHRow.Cells.Add(tHeader);
tblCompLoc1.Rows.Add(tHRow);
DataTable dtCat = new DataTable();
dtCat = SQLCon.SQLCommand_DokuTool("SELECT CL.ID, C.CatName FROM TBL_Ref_CatLoc AS CL, TBL_Category AS C WHERE C.CatID = CL.CatID AND CL.LocID = '" + dr.Field<Guid>("ID").ToString() + "' AND CL.Approved='True' ORDER BY CatName ASC");
foreach (DataRow dr2 in dtCat.Rows)
{
//Working as plain Text
//TableRow tRow = new TableRow();
//TableCell tCell = new TableCell();
//tCell.Text = dr2.Field<string>("CatName");
//tRow.Cells.Add(tCell);
//tblCompLoc1.Rows.Add(tRow);
//Not working as Hyperlink or Btn
TableRow tRow = new TableRow();
TableCell tCell = new TableCell();
HyperLink hl = new HyperLink();
hl.EnableViewState=true;
hl.Text = dr2.Field<string>("CatName");
string gLocID = SQLCon.SQLCommand_User("SELECT ID FROM TBL_Location WHERE fCompanyID = '"+sRequest+"' AND City + ', ' + Street1 ='"+tHeader.Text+"'").Rows[0].Field<Guid>("ID").ToString();
string gCatID = SQLCon.SQLCommand_DokuTool("SELECT CatID FROM TBL_Category WHERE CatName='"+hl.Text+"'").Rows[0].Field<Guid>("CatID").ToString();
string sRequestedCat = SQLCon.SQLCommand_DokuTool("SELECT ID FROM TBL_Ref_CatLoc WHERE LocID = '"+gLocID+"' AND CatID='"+gCatID+"'").Rows[0].Field<Guid>("ID").ToString();
hl.NavigateUrl="~/Default?ID="+sRequestedCat;
tCell.Controls.Add(hl);
tRow.Controls.Add(tCell);
tblCompLoc1.Rows.Add(tRow);
}
I want to create a Table which is filled from DataBase and can look different on each site and every Table Cell should have a different Link where it leads the user. The table creation starts on page init.

Related

Dynamically created panels not responding to CSS for alignment

I am working on a website that will act as a blog. My issue is with the comments section and it deals with the alignment of child comment panels. I try to add CSS to float the panels right, but they stay on the left. I have also tried setting the HorizontalAlign of the parent panels to right.
For more context, this is an image of the comments section:
As you can see, the child comments panels are sticking to the left.
This is the method where I am dynamically creating the comments section into an exiting panel called Panel1.
protected void drawComments(string ID, int NumTabs, Panel parentPanel) {
string hash = ID;
SqlConnection conn = new SqlConnection(Secret Stuff);
string cmdStr = "SELECT * FROM Comments WHERE ParentID=#searchHash";
SqlCommand cmd = new SqlCommand(cmdStr, conn);
cmd.Parameters.Add("#searchHash", SqlDbType.NVarChar).Value = hash;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
Panel tempPanel;
if (reader.HasRows)
{
while (reader.Read())
{
ID = reader.GetString(4);
tempPanel = new Panel();
tempPanel.BorderStyle = BorderStyle.Solid;
tempPanel.BorderColor = System.Drawing.ColorTranslator.FromHtml("#2461bf");
tempPanel.Width = new Unit((100 - (NumTabs * 5)).ToString() + "%");
tempPanel.Attributes.Add("style", "margin-left:auto;");
tempPanel.Attributes.Add("style", "margin-right:auto;");
if (NumTabs > 0)
{
tempPanel.Attributes.Add("style", "margin-bottom:5px");
// tempPanel.Attributes.Add("style", "border-top-style:none");
tempPanel.Attributes.Add("style", "border-left-style:none");
// tempPanel.Attributes.Add("style", "border-right-style:solid");
tempPanel.Attributes.Add("style", "border-bottom-style:none");
}
else
{
tempPanel.Attributes.Add("style", "margin-top:50px");
// Panel1.Controls.Add(new LiteralControl("<BR />"));
}
Label currComment = new Label();
Label currAuthor = new Label();
currComment.Text = reader.GetString(0);
currAuthor.Text = reader.GetString(3).Split('#')[0];
Table tbl = new Table();
tbl.Width = new Unit("100%");
tbl.Attributes.Add("style", "margin-left:auto");
tbl.Attributes.Add("style", "margin-right:auto");
TableRow tblrow1 = new TableRow();
TableCell tblcell11 = new TableCell();
TableCell tblcell12 = new TableCell();
tblcell11.HorizontalAlign = HorizontalAlign.Right;
tblcell11.Width = new Unit("30%");
tblcell11.Text = currAuthor.Text + " Says:";
tblcell12.HorizontalAlign = HorizontalAlign.Left;
tblcell12.Text = currComment.Text;
tblcell12.Width = new Unit("70%");
tblrow1.Cells.Add(tblcell11);
tblrow1.Cells.Add(tblcell12);
tbl.Rows.Add(tblrow1);
TableCell tblcell21 = new TableCell();
tblcell21.Width = new Unit("30%");
ImageButton replyButton = new ImageButton();
replyButton.ImageUrl = "~/images/replybutton.png";
replyButton.Attributes.Add("style", "float:right");
replyButton.Width = 77;
replyButton.ID = ID;
replyButton.Command += addReply;
ImageButton likeButton = new ImageButton();
likeButton.ImageUrl = "~/images/likebutton.png";
likeButton.Attributes.Add("style", "float:right");
likeButton.Width = 65;
Label likeCount = new Label();
likeCount.Attributes.Add("style", "float:right");
likeCount.BorderStyle = BorderStyle.Groove;
likeCount.Text = "0";
TableCell tblcell22 = new TableCell();
tblcell22.HorizontalAlign = HorizontalAlign.Left;
tblcell22.Controls.Add(likeCount);
tblcell22.Controls.Add(likeButton);
tblcell22.Controls.Add(replyButton);
tblcell22.Width = new Unit("70%");
TableRow tblrow2 = new TableRow();
tblrow2.Cells.Add(tblcell21);
tblrow2.Cells.Add(tblcell22);
tbl.Rows.Add(tblrow2);
tempPanel.Controls.Add(tbl);
//tempPanel.Controls.Add(currComment);
if (NumTabs>0)
{
parentPanel.Controls.Add(tempPanel);
}
else
Panel1.Controls.Add(tempPanel);
drawComments(reader.GetString(4), NumTabs + 1, tempPanel);
}
}
}
catch (Exception ex)
{
lblDebug.Text = ex.ToString();
}
finally { conn.Close(); }
}
Any suggestions to get these child panels right aligning would be greatly appreciated. I hope you can understand what I am going for through this poorly written code by a 15 year old.

Setting Rowspan for Dynamic Rows in asp.net Table Control

I've created an asp.net table and added rows to the table dynamically that is using Backend ( C# ) .
The First Column of the Rows should have Rowspan .
The rows are being added very fine and the Rowspan is also added fine but when the Postback occurs , The Rowspans gets changes automatically .
Can any one please help me to solve this problem :(
This is when the page loads First Time:
This is when PostBack Occured First Time :
This is when Postback Occured Second Time :
Thanks in advance
Here is my complete code :
.aspx Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style>
.tbl {
border:1px solid #000000;
}
.tbl td,th {
border:1px solid #000000;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Table runat="server" ID="tbl_fund" CssClass="tbl"></asp:Table>
<asp:Button runat="server" Text="Do Post Back" />
</div>
</form>
</body>
</html>
C# Code :
protected void Page_Load(object sender, EventArgs e)
{
PrintFundChanges();
}
public void PrintFundChanges()
{
//***************************Header Started*****************************
TableRow tr_head = new TableRow();
TableHeaderCell th1 = new TableHeaderCell();
th1.Text = "CNIC";
TableHeaderCell th2 = new TableHeaderCell();
th2.Text = "Field Name";
TableHeaderCell th3 = new TableHeaderCell();
th3.Text = "Updated Value";
TableHeaderCell th4 = new TableHeaderCell();
th4.Text = "Current Value";
TableHeaderCell th5 = new TableHeaderCell();
CheckBox chk_head = new CheckBox();
chk_head.ID = "chk_fund";
chk_head.CheckedChanged += new EventHandler(Chk_Fund_CheckedChanged);
chk_head.Text = "Approve / Disapprove";
chk_head.AutoPostBack = true;
th5.Controls.Add(chk_head);
TableHeaderCell th6 = new TableHeaderCell();
th6.Text = "Table Name";
th6.Style.Add("display", "none");
TableHeaderCell th7 = new TableHeaderCell();
th7.Text = "Column Name";
th7.Style.Add("display", "none");
TableHeaderCell th8 = new TableHeaderCell();
th8.Text = "pk_code";
th8.Style.Add("display", "none");
TableHeaderCell th9 = new TableHeaderCell();
th9.Text = "pk2_code";
th9.Style.Add("display", "none");
TableHeaderCell th10 = new TableHeaderCell();
th10.Text = "action_type";
th10.Style.Add("display", "none");
th1.Style.Add("width", "20%");
th2.Style.Add("width", "20%");
th3.Style.Add("width", "20%");
th4.Style.Add("width", "20%");
tr_head.Cells.Add(th1);
tr_head.Cells.Add(th2);
tr_head.Cells.Add(th3);
tr_head.Cells.Add(th4);
tr_head.Cells.Add(th5);
tr_head.Cells.Add(th6);
tr_head.Cells.Add(th7);
tr_head.Cells.Add(th8);
tr_head.Cells.Add(th9);
tr_head.Cells.Add(th10);
tbl_fund.Rows.Add(tr_head);
//****************************Header Ended*******************************
//****************************Print Updated Data Started*************************
//Getting distinct primary key data
//DataTable dt_DistinctPk = dt_FundUpdatedFields.DefaultView.ToTable(true, "pk_code");
DataTable dt_DistinctPk = new DataTable();
dt_DistinctPk.Columns.Add(new DataColumn("pk_code", typeof(string)));
DataRow dr = dt_DistinctPk.NewRow();
dr["pk_code"] = "123";
dt_DistinctPk.Rows.Add(dr);
dr = dt_DistinctPk.NewRow();
dr["pk_code"] = "456";
dt_DistinctPk.Rows.Add(dr);
for (int i = 0; i < dt_DistinctPk.Rows.Count; i++)
{
TableCell td_pk = new TableCell();
td_pk.Text = "<b style='font-size:13px !important;'>" + dt_DistinctPk.Rows[i]["pk_code"].ToString() + "</b>";
//int numberOfRecords = dt_FundUpdatedFields.Select("pk_code = " + dt_DistinctPk.Rows[i]["pk_code"].ToString()).Length;
int numberOfRecords =5;
td_pk.RowSpan = numberOfRecords;
bool IsAddAtOnce = true;
for (int j = 0; j < 5; j++)
{
string field_name_lable = "Column name here";
TableRow tr = new TableRow();
TableCell td1 = new TableCell();
td1.Text = field_name_lable;
TableCell td2 = new TableCell();
TableCell td3 = new TableCell();
td2.Text = "New Value here";
td3.Text = "Old Value here";
TableCell td4 = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "chk_" +j;
//td4.Controls.Add(chk);
TableCell td5 = new TableCell();
td5.Text = "tbl_name";
td5.Style.Add("display","none");
TableCell td6 = new TableCell();
td6.Text = "field_name";
td6.Style.Add("display", "none");
TableCell td7 = new TableCell();
td7.Text = j.ToString();
td7.Style.Add("display", "none");
TableCell td8 = new TableCell();
td8.Text = j.ToString();
td8.Style.Add("display", "none");
TableCell td9 = new TableCell();
td9.Text = "1";
td9.Style.Add("display", "none");
if (IsAddAtOnce)
{
tr.Cells.Add(td_pk);
IsAddAtOnce = false;
}
tr.Cells.Add(td1);
tr.Cells.Add(td2);
tr.Cells.Add(td3);
tr.Cells.Add(td4);
tr.Cells.Add(td5);
tr.Cells.Add(td6);
tr.Cells.Add(td7);
tr.Cells.Add(td8);
tr.Cells.Add(td9);
tbl_fund.Rows.Add(tr);
if (j ==5 - 1)//Last Termination of Loop
{
//Printing Attachments
td_pk.RowSpan = td_pk.RowSpan + 1;
td1 = new TableCell();
td1.Text = "CNIC Attachment";
td2 = new TableCell();
Image img_new = new Image();
// img_new.ImageUrl = "ImgHandler.ashx?typ=Newfund&emp=" + Requestor + "&pk=" + dt_FundUpdatedAttachments.Rows[k]["pk_code"].ToString();
td2.Controls.Add(img_new);
td3 = new TableCell();
Image img_old = new Image();
//img_old.ImageUrl = "ImgHandler.ashx?typ=Currfund&emp=" + Requestor + "&pk=" + dt_FundUpdatedAttachments.Rows[k]["pk_code"].ToString();
td3.Controls.Add(img_old);
td4 = new TableCell();
chk = new CheckBox();
//chk.ID = "chk_" + dt_FundUpdatedAttachments.Rows[k]["tbl_name"].ToString().ToUpper() + "_" + dt_FundUpdatedAttachments.Rows[k]["field_name"].ToString().ToUpper() + "_" + dt_FundUpdatedAttachments.Rows[k]["pk_code"].ToString().ToUpper() + "_";
td4.Controls.Add(chk);
td5 = new TableCell();
td5.Text = "tbl_name";
td5.Style.Add("display", "none");
td6 = new TableCell();
td6.Text ="field_name";
td6.Style.Add("display", "none");
td7 = new TableCell();
td7.Text = j.ToString();
td7.Style.Add("display", "none");
td8 = new TableCell();
td8.Text = "";
td8.Style.Add("display", "none");
td9 = new TableCell();
td9.Text = "1";
td9.Style.Add("display", "none");
tr = new TableRow();
tr.Cells.Add(td1);
tr.Cells.Add(td2);
tr.Cells.Add(td3);
tr.Cells.Add(td4);
tr.Cells.Add(td5);
tr.Cells.Add(td6);
tr.Cells.Add(td7);
tr.Cells.Add(td8);//pk2_code
tr.Cells.Add(td9);//action_type
tbl_fund.Rows.Add(tr);
}
}
}
////****************************Print New Data Ended***************************
TableRow tr_blank = new TableRow();
TableCell td_blank = new TableCell();
td_blank.Text = "Deleted Data";
td_blank.Style.Add("font-weight", "bold !important");
td_blank.Style.Add("font-size", " 16px !important");
td_blank.Style.Add("background-color", "#e3e3e3 !important");
td_blank.ColumnSpan = 10;
tr_blank.Cells.Add(td_blank);
tbl_fund.Rows.Add(tr_blank);
////****************************Print Deleted Data Started***************************
//****************************Print Deleted Data Ended***************************
}
protected void Chk_Fund_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
bool IsChecked = chk.Checked;
for (int i = 1; i < tbl_fund.Rows.Count; i++)
{
string pk_code = "";
string tbl_name = "";
string col_name = "";
string pk2_code = "";
int CellsCount = tbl_fund.Rows[i].Cells.Count;
/*In this table rowspan is used for printing cnic number,
so the row who has rowspan will have cnic column in first termination ,
while in second termination the cell count will decrease because the
row before the current row will having the rowspan.
*/
if (CellsCount == 10)
{
tbl_name = tbl_fund.Rows[i].Cells[5].Text;
col_name = tbl_fund.Rows[i].Cells[6].Text;
pk_code = tbl_fund.Rows[i].Cells[7].Text;
pk2_code = tbl_fund.Rows[i].Cells[8].Text;
}
else if (CellsCount == 9)
{
tbl_name = tbl_fund.Rows[i].Cells[4].Text;
col_name = tbl_fund.Rows[i].Cells[5].Text;
pk_code = tbl_fund.Rows[i].Cells[6].Text;
pk2_code = tbl_fund.Rows[i].Cells[7].Text;
}
if (tbl_name != "")//if it is not a blank/header row
{
CheckBox ck = new CheckBox();
string chk_id = "chk_" + tbl_name + "_" + col_name + "_" + pk_code + "_" + pk2_code;
ck = (CheckBox)tbl_fund.Rows[i].Cells[4].FindControl(chk_id);//chk_tblname_colname_pk
ck.Checked = IsChecked;
}
}
}
just change the this line from
td_pk.RowSpan = td_pk.RowSpan + 1;
to
td_pk.RowSpan = numberOfRecords + 1;

Find dynamically generated text on button click

I'm using asp.net C# in my project we have dynamically generated textbox inside panel I want to get textbox value,so I'm using the foreach loop for getting the Textbox but I'm not getting the textbox
Here I generate the control
Table table = new Table();
table.ID = "table1";
table.Width = new Unit("100%");
table.BorderWidth = new Unit("1px");
table.CssClass = "tbl";
string Query = "SELECT * FROM XXCUS.MASTER_VERIFICATION";
OracleDataAdapter da = new OracleDataAdapter(Query, obj_Conn);
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableHeaderCell cellheader = new TableHeaderCell();
Label lblHeader = new Label();
lblHeader.Text = "Select";
Label lblDesc = new Label();
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thcode = new TableHeaderCell();
TableHeaderCell thcReason = new TableHeaderCell();
thc.Text = "Select";
thcode.Text = "Description";
thcReason.Text = "Reason";
thr.Cells.Add(thc);
thr.Cells.Add(thcode);
//thr.CssClass = "pdlbl";
thc.Width = new Unit("5px");
thcode.Width = new Unit("75%");
thcode.CssClass = "thcode";
thcReason.Width = new Unit("20%");
thcReason.CssClass = "thcReason";
thr.Cells.Add(thcReason);
table.Rows.Add(thr);
for (int i = 0; i < Count; i++)
{
TableRow row = new TableRow();
TableCell cellchk = new TableCell();
TableCell celltxt = new TableCell();
TableCell celldesc = new TableCell();
TextBox txt = new TextBox();
CheckBox chk = new CheckBox();
txt.ID = "txt" + i.ToString();
txt.MaxLength = 250;
//txt.Width = new Unit("84%");
//txt.CssClass = "txtCl";
chk.ID = "chk" + i.ToString();
txt.TextMode = TextBoxMode.MultiLine;
cellchk.ID = "cellchk" + i.ToString();
celltxt.ID = "celltxt" + i.ToString();
cellchk.Controls.Add(chk);
//chk.Attributes.Add("onClick", "alert('" + chk.ID + "')");
Label lblDescription = new Label();
lblDescription.Text = dt.Rows[i]["DESCRIPTION"].ToString();
celldesc.Controls.Add(lblDescription);
cellheader.Controls.Add(lblHeader);
cellchk.Width = new Unit("5%");
//cellchk.CssClass = "pd";
celldesc.Width = new Unit("75%");
//celldesc.CssClass = "pdlbl";
celltxt.Width = new Unit("20%");
celltxt.Controls.Add(txt);
row.Cells.Add(cellchk);
row.Cells.Add(celldesc);
row.Cells.Add(celltxt);
table.Rows.Add(row);
}
dvGenerateCntrl.Controls.Add(table);
}
and I'm using the panel for add the control
<asp:Panel ID="dvGenerateCntrl" runat="server">
</asp:Panel>
I don't see any issues with your above code so maybe the issue is how you adding the textbox control to dvGenerateCntrol.
Can you show this code as well.
Here is some example code of adding a control to a cell within a table and then finding then iterating through the rows and cells to find the textbox.
Table t = new Table();
TableRow tr = new TableRow();
TableCell tc = new TableCell();
System.Web.UI.WebControls.TextBox tb = new System.Web.UI.WebControls.TextBox() { Text = "Testing" };
tc.Controls.Add(tb); //Add Textbox to TableCell Control Collection
tr.Cells.Add(tc); // Add TableCell to TableRow
t.Rows.Add(tr); //Add TableRow to Table
System.Web.UI.WebControls.Panel panel = new System.Web.UI.WebControls.Panel(); //This is your panel
panel.Controls.Add(t); // Add Table to Panel
Table tbl = panel.Controls.OfType<Table>().FirstOrDefault(); //Now to find the TextBox in the Table, in the Row, in the cell
foreach (TableRow row in tbl.Rows) //Loop through each TableRow
{
foreach (TableCell cell in row.Cells) //Loop through each TableCell
{
IEnumerable<System.Web.UI.WebControls.TextBox> txtBoxes = cell.Controls.OfType<System.Web.UI.WebControls.TextBox>(); //Search TableCell.Controls Collection for all TextBoxes
}
}

C#.net how to add an image into a table cell dynamically by code

I am trying to add an image into a table that I'm making dynamically by code behind.
However the image is not added to the cell.
All the other codes I'm finding are talking about an htmltable which is not the same as table();
public partial class Children_nihul_1 : System.Web.UI.Page
{
protected string mychildrenlist;
protected void Page_Init(object sender, EventArgs e)
{
var cases = new List<string>();
System.Web.UI.WebControls.Image myGamepic1 = new System.Web.UI.WebControls.Image();
// var myGamepic1 = new Image();
myGamepic1.ImageUrl = "~/img/inner-page/Game1.png";
myGamepic1.Height = 30;
//this part is only a call for data from database- not relavent to the
qustion./
DataSet ds = new DataSet();
string x = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("./App_Data/DatabaseGames.accdb") + ";";
string y = "select * from Students";
mySql myq = new mySql();
ds = myq.sqlRet(x, y);
rowlist = ds.Tables[0].Rows.Count;
for (int i = 0; i < rowlist; ++i)
{
cases.Add(ds.Tables[0].Rows[i][1].ToString());
}
//my table creation
Table table = new Table();
table.BorderStyle = BorderStyle.None;
//Add Header Row
TableRow row = new TableRow();
TableHeaderCell headerCell = new TableHeaderCell();
headerCell.Text = "aaa";
row.Controls.Add(headerCell);
headerCell = new TableHeaderCell();
headerCell.Text = "ccc";
row.Controls.Add(headerCell);
table.Controls.Add(row);
for (int i = 0; i < rowlist; ++i)
{
//Add DataRow
row = new TableRow();
TableCell cell = new TableCell();
cell.Text = cases[i];
row.Controls.Add(cell);
cell = new TableCell();
cell.Controls.Add(myGamepic1);
row.Controls.Add(cell);
table.Controls.Add(row);
}
Panel1.Controls.Add(table);
Panel1.Controls.Add(myGamepic1);
}
}
Try something like this. Works for me when adding an image dynamic using code behind.
cell11.Text = string.Format("<img src='images/close_icon.png' />");

asp.net c# adding multiple tablerows to table only results in one row

I have to add a selection of data from the database to a table dynamically. To do so I have created a table that has rows added to it in a loop. However it only really adds the final row. I assume it's something to do with the naming? Below is the code I'm using. It returns the table, formatted correctly with the header, but only one row of data...
protected Table listVolunteers()
{
// Query to get volunteer information
string query = "SELECT gvo_id, gvo_name, gvo_email, gvo_mobile_ph, gvo_dob, gvo_status FROM volunteer";
// Table will hold the following information on volunteers:
// ID, Name, Email, Mobile, DOB, Status
// As well as a check box to do mass delete, a view button and an edit button on each
Table result = new Table();
result.ID = "volunteers";
result.CssClass = "list";
result.CellSpacing = 0;
// Creater table header
TableHeaderRow header = new TableHeaderRow();
header.CssClass = "header";
TableHeaderCell id = new TableHeaderCell();
id.CssClass = "id";
id.Width = 10;
id.Text = "ID";
header.Cells.Add(id);
TableHeaderCell name = new TableHeaderCell();
name.CssClass = "name";
name.Text = "NAME";
header.Cells.Add(name);
TableHeaderCell email = new TableHeaderCell();
email.CssClass = "email";
email.Text = "EMAIL";
header.Cells.Add(email);
TableHeaderCell mobile = new TableHeaderCell();
mobile.CssClass = "mobile";
mobile.Width = 70;
mobile.Text = "MOBILE #";
header.Cells.Add(mobile);
TableHeaderCell dob = new TableHeaderCell();
dob.CssClass = "dob";
dob.Width = 50;
dob.Text = "D.O.B";
header.Cells.Add(dob);
TableHeaderCell status = new TableHeaderCell();
status.CssClass = "status";
status.Width = 50;
status.Text = "STAT";
header.Cells.Add(status);
TableHeaderCell check = new TableHeaderCell();
check.CssClass = "check";
check.Width = 13;
header.Cells.Add(check);
TableHeaderCell view = new TableHeaderCell();
view.CssClass = "button";
view.Width = 50;
header.Cells.Add(view);
TableHeaderCell edit = new TableHeaderCell();
edit.CssClass = "button";
edit.Width = 50;
header.Cells.Add(edit);
// Add header to table
result.Rows.Add(header);
//Declaration for following code
TableCell rid = new TableCell();
rid.CssClass = "id";
TableCell rname = new TableCell();
rname.CssClass = "name";
TableCell remail = new TableCell();
remail.CssClass = "email";
TableCell rmobile = new TableCell();
rmobile.CssClass = "mobile";
TableCell rdob = new TableCell();
rdob.CssClass = "dob";
TableCell rstatus = new TableCell();
rstatus.CssClass = "status";
TableCell rcheck = new TableCell();
rcheck.CssClass = "check";
TableCell rview = new TableCell();
rview.CssClass = "button";
TableCell redit = new TableCell();
redit.CssClass = "button";
CheckBox chk = new CheckBox();
chk.Checked = false;
Button btnView = new Button();
btnView.Text = "View";
Button btnEdit = new Button();
btnEdit.Text = "Edit";
string rowClass = "odd";
Vector<TableRow> rows = new Vector<TableRow>();
// Add volunteers to table
try
{
using (conn)
{
conn.Open();
cmd = new OleDbCommand(query, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DateTime temp = new DateTime();
rid.Text = rdr.GetValue(0).ToString();
rname.Text = rdr.GetValue(1).ToString();
remail.Text = rdr.GetValue(2).ToString();
rmobile.Text = rdr.GetValue(3).ToString();
DateTime.TryParse(rdr.GetValue(4).ToString(), out temp);
rdob.Text = temp.ToString("dd/MM/yy");
rstatus.Text = rdr.GetValue(5).ToString();
chk.ID = rid.Text;
btnView.PostBackUrl = string.Format("/VolunteerView.aspx?ID={0}", rid.Text);
btnEdit.PostBackUrl = string.Format("/VolunteerEdit.aspx?ID={0}", rid.Text);
rcheck.Controls.Add(chk);
rview.Controls.Add(btnView);
redit.Controls.Add(btnEdit);
TableRow row = new TableRow();
if (rowClass == "even")
rowClass = "odd";
else
rowClass = "even";
row.CssClass = rowClass;
// Add cells to row
row.Cells.Add(rid);
row.Cells.Add(rname);
row.Cells.Add(remail);
row.Cells.Add(rmobile);
row.Cells.Add(rdob);
row.Cells.Add(rstatus);
row.Cells.Add(rcheck);
row.Cells.Add(rview);
row.Cells.Add(redit);
// Add row to table
rows.Add(row);
}
TableRow[] array = new TableRow[rows.Count];
for (int i = 0; i < rows.Count; i++)
{
array[i] = rows[i];
}
result.Rows.AddRange(array);
}
}
catch (Exception e)
{
TableCell error = new TableCell();
TableRow row = new TableRow();
error.ColumnSpan = 9;
error.CssClass = "error";
error.Text = "An error occurred while loading the volunteers";
row.Cells.Add(error);
result.Rows.Add(row);
}
finally
{
if (rdr != null)
rdr.Close();
}
if (conn != null)
conn.Close();
return result;
}
Try using the ImportRow method()
result.ImportRow(row);
You can replace where you are doing the following :
// Add row to table
rows.Add(row);
And use the ImportRow method. That's all there is to it, you should not need further code.
Okay so I solved the problem thanks to this post.
Pretty much all I had to do was ensure I was creating a new row / cell in the loop. To show you what I mean, the following shows my now functioning loop.
while (rdr.Read())
{
DateTime temp = new DateTime();
// This is the code that was added in.
rid = new TableCell();
rname = new TableCell();
remail = new TableCell();
rmobile = new TableCell();
rdob = new TableCell();
rstatus = new TableCell();
rcheck = new TableCell();
rview = new TableCell();
redit = new TableCell();
chk = new CheckBox();
btnView = new Button();
btnEdit = new Button();
// Because I was creating new controls I also had to move my css classes to the loop as well
rid.CssClass = "id";
rname.CssClass = "name";
remail.CssClass = "email";
rmobile.CssClass = "mobile";
rdob.CssClass = "dob";
rstatus.CssClass = "status";
rcheck.CssClass = "check";
rview.CssClass = "button";
redit.CssClass = "button";
chk.Checked = false;
btnView.Text = "View";
btnEdit.Text = "Edit";
rid.Text = rdr.GetValue(0).ToString();
rname.Text = rdr.GetValue(1).ToString();
remail.Text = rdr.GetValue(2).ToString();
rmobile.Text = rdr.GetValue(3).ToString();
DateTime.TryParse(rdr.GetValue(4).ToString(), out temp);
rdob.Text = temp.ToString("dd/MM/yy");
rstatus.Text = rdr.GetValue(5).ToString();
chk.ID = rid.Text;
btnView.PostBackUrl = string.Format("/VolunteerView.aspx?ID={0}", rid.Text);
btnEdit.PostBackUrl = string.Format("/VolunteerEdit.aspx?ID={0}", rid.Text);
rcheck.Controls.Add(chk);
rview.Controls.Add(btnView);
redit.Controls.Add(btnEdit);
row = new TableRow();
if (rowClass == "even")
rowClass = "odd";
else
rowClass = "even";
row.CssClass = rowClass;
// Add cells to row
row.Cells.Add(rid);
row.Cells.Add(rname);
row.Cells.Add(remail);
row.Cells.Add(rmobile);
row.Cells.Add(rdob);
row.Cells.Add(rstatus);
row.Cells.Add(rcheck);
row.Cells.Add(rview);
row.Cells.Add(redit);
// Add row to table
result.Rows.Add(row);
}

Categories