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.
Related
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
}
}
I am developing a shopping cart kind of thing. For that, on selecting products they get added to a temporary table, and so on. Then a popup window opens which loads dynamic labels, text-boxes and linkbutton based on the number of rows in the temporary table in the page load event. I want to allow users to change the textbox field which is the quantity of the product, and immediately update in the database using the dynamically created linkbutton.
I tried using Viewstate but I am unable to do it according to my need. Also , I read many other articles and posts on stack-overflow and other blogs too, but could not work out.
Here is my code:-
protected void Page_Load(object sender, EventArgs e)
{
Session["date"] = DateTime.Now.ToShortDateString();
productListing();
LabelCost.Text = total.ToString("F");
}
public void productListing()
{
//...................................Product Listing...............................
con2.Close();
con2.Open();
SqlDataAdapter adp12 = new SqlDataAdapter("select * from db_temporary_cart where(IP_address='" + Request.QueryString["ip"].ToString() + "' AND date='" + Session["date"] + "') ORDER BY counter DESC", con2);
DataSet ds12 = new DataSet();
adp12.Fill(ds12, "db_temporary_cart");
int count12 = ds12.Tables[0].Rows.Count;
if (count12 > 0)
{
totalProductRpwsincategory = count12;
//................storing products id of the category.....................
arr_product_id = new string[count12];
arr_product_name = new string[count12];
arr_product_qty = new int[count12];
arr_product_price = new double[count12];
arr_product_subtotal = new double[count12];
for (int i = 0; i < count12; i++)
{
arr_product_id[i] = ds12.Tables[0].Rows[i]["product_id"].ToString();
arr_product_qty[i] = Convert.ToInt32(ds12.Tables[0].Rows[i]["quantity"]);
}
con2.Close();
for (int i = 0; i < arr_product_id.Length; i++)
{
con2.Close();
con3.Close();
con3.Open();
SqlDataAdapter adp123 = new SqlDataAdapter("select * from db_product_management where(product_id='" + arr_product_id[i].ToString() + "' AND product_stock_availability='" + "In-Stock" + "')", con3);
DataSet ds123 = new DataSet();
adp123.Fill(ds123, "db_product_management");
int count123 = ds123.Tables[0].Rows.Count;
if (count123 > 0)
{
arr_product_name[i] = ds123.Tables[0].Rows[0]["product_name"].ToString();
arr_product_price[i] = Convert.ToDouble(ds123.Tables[0].Rows[0]["product_price"]);
arr_product_subtotal[i] = Convert.ToDouble((arr_product_price[i])*(arr_product_qty[i]));
total = total + arr_product_subtotal[i];
con3.Close();
}
con3.Close();
}
//................storing products id of the category.....................
Table table = new Table();
var collection = new List<string>();
for (int i = 0; i < totalProductRpwsincategory; i++)
{
TableRow row = new TableRow();
row.CssClass = "dynamicMain";
System.Web.UI.HtmlControls.HtmlGenericControl createDivMain = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDivMain.Attributes["class"] = "dynamicMain";
ImageButton imgLink = new ImageButton();
imgLink.Attributes.Add("width", "150px");
imgLink.Attributes.Add("height", "104px");
imgLink.Attributes["class"] = "dynamicIMG";
imgLink.CommandArgument = arr_product_id[i];
imgLink.CommandName = arr_product_name[i];
imgLink.Command += new CommandEventHandler(this.OnDynamicLinkButtonClick);
System.Web.UI.HtmlControls.HtmlGenericControl createDiv1 = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv1.Attributes["class"] = "sub-category-productsDisplayBlockText1_Dynamic";
Label linkProduct = new Label();
linkProduct.Text = arr_product_name[i];
LinkButton linkSaveQty = new LinkButton();
linkSaveQty.Text = arr_product_name[i];
linkSaveQty.Font.Underline = false;
linkSaveQty.ID = i.ToString();
linkSaveQty.Text = "Save";
linkSaveQty.CommandArgument = arr_product_id[i];
linkSaveQty.Attributes["class"] = "dynamicSaveQty";
linkSaveQty.Command += new CommandEventHandler(this.OnDynamicLinkButtonClickSave);
//linkSaveQty.CausesValidation = false;
System.Web.UI.HtmlControls.HtmlGenericControl createDivTb = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
TextBox tb = new TextBox();
//tb.ID = arr_product_id[i] + Guid.NewGuid().ToString("N");
tb.ID = arr_product_id[i];
tb.Text = arr_product_qty[i].ToString();
tb.Attributes["class"] = "dynamicTB";
Label linkQty = new Label();
linkQty.Text = "Quantity";
linkQty.Attributes["class"] = "dynamicQty";
collection.Add(tb.ID);
System.Web.UI.HtmlControls.HtmlGenericControl createDiv3 = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv3.Attributes["class"] = "sub-category-productsDisplayBlockText1_Dynamic_Price";
Label linkPrice = new Label();
linkPrice.Text = arr_product_price[i].ToString();
System.Web.UI.HtmlControls.HtmlGenericControl createDiv2 = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv2.Attributes["class"] = "sub-category-productsDisplayBlockText1_Dynamic_SubTotal";
Label linkSubTotal = new Label();
linkSubTotal.Text = arr_product_subtotal[i].ToString();
ImageButton imgLinkDelete = new ImageButton();
imgLinkDelete.Attributes.Add("width", "25px");
imgLinkDelete.Attributes.Add("height", "25px");
imgLinkDelete.CommandArgument = arr_product_id[i];
imgLinkDelete.Command += new CommandEventHandler(this.OnDynamicLinkButtonClickDelete);
for (int j = 0; j < 1; j++)
{
imgLink.ImageUrl = "NImageMainProductImage.ashx?PhotoId=" + arr_product_id[i];
TableCell cell = new TableCell();
cell.Controls.Add(imgLink);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 1; j < 2; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(createDiv1);
createDiv1.Controls.Add(linkProduct);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 2; j < 3; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(linkQty);
cell.Controls.Add(new LiteralControl("<br>"));
cell.Controls.Add(tb);
cell.Controls.Add(new LiteralControl("<br>"));
cell.Controls.Add(linkSaveQty);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 3; j < 4; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(createDiv3);
createDiv3.Controls.Add(linkPrice);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 4; j < 5; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(createDiv2);
createDiv2.Controls.Add(linkSubTotal);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 5; j < 6; j++)
{
imgLinkDelete.ImageUrl = "../../images/delete.png";
TableCell cell = new TableCell();
cell.Controls.Add(imgLinkDelete);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
table.Rows.Add(row);
}
TextBoxIdCollection = collection;
PanelItemsCart.Controls.Add(table);
con2.Close();
}
con2.Close();
//...................................Product Listing...............................
}
This was my code for loading dynamic controls on page load event. Here is the Enumeration string and click event of the dynamically created link button, which is not working.
private List<string> TextBoxIdCollection
{
get
{
var collection = ViewState["TextBoxIdCollection"] as List<string>;
return collection ?? new List<string>();
}
set { ViewState["TextBoxIdCollection"] = value; }
}
void OnDynamicLinkButtonClickSave(object sender, CommandEventArgs e)
{
LinkButton clickedButton = (LinkButton)sender;
String commandArgument = clickedButton.CommandArgument;
int value = 0;
foreach (Control c in PanelItemsCart.Controls)
{
if (c.GetType() == typeof(TextBox) && c.ID == (commandArgument))
{
value = Convert.ToInt32(((TextBox)c).Text);
con4.Close();
con4.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from db_temporary_cart where((IP_address='" + Request.QueryString["ip"].ToString() + "' AND date='" + DateTime.Now.ToShortDateString() + "') AND (product_id='" + commandArgument + "'))", con4);
DataSet ds = new DataSet();
adp.Fill(ds, "db_temporary_cart");
int cd = ds.Tables[0].Rows.Count;
if (cd > 0)
{
int sendQty = value;
con4.Close();
con3.Close();
con3.Open();
SqlCommand cmd4 = new SqlCommand("UPDATE db_temporary_cart SET quantity='" + sendQty + "' where((IP_address='" + Request.QueryString["ip"].ToString() + "' AND date='" + DateTime.Now.ToShortDateString() + "') AND (product_id='" + commandArgument + "'))", con3);
cmd4.ExecuteNonQuery();
con3.Close();
}
con4.Close();
PanelItemsCart.Controls.Clear();
productListing();
}
}
}
Kindly, help me enter all the textboxes' and labels', which are dynamically created, values in the database on click event of dynamically created linkbuttons.
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' />");
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);
}
I have created dynamically a Grid control with two columns and populate its Rows using data from the database in first column and a textbox control in the second column. But the last two rows of grid gets overlapped.
The following is my code snippet.
if (comboBox1.SelectedIndex > 0)
{
// Create the Grid
Grid DynamicGrid = new Grid();
DynamicGrid.Width = 400;
DynamicGrid.HorizontalAlignment = HorizontalAlignment.Left;
DynamicGrid.VerticalAlignment = VerticalAlignment.Top;
DynamicGrid.ShowGridLines = true;
DynamicGrid.Background = new SolidColorBrush(Colors.LightSteelBlue);
//Adding columns to datagrid
ColumnDefinition gridCol1 = new ColumnDefinition();
ColumnDefinition gridCol2 = new ColumnDefinition();
DynamicGrid.ColumnDefinitions.Add(gridCol1);
DynamicGrid.ColumnDefinitions.Add(gridCol2);
// Add first column header
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = "Particulars";
txtBlock1.FontSize = 14;
txtBlock1.FontWeight = FontWeights.Bold;
txtBlock1.Foreground = new SolidColorBrush(Colors.Green);
txtBlock1.VerticalAlignment = VerticalAlignment.Top;
Grid.SetRow(txtBlock1, 0);
Grid.SetColumn(txtBlock1, 0);
// Add second column header
TextBlock txtBlock2 = new TextBlock();
txtBlock2.Text = "Amount";
txtBlock2.FontSize = 14;
txtBlock2.FontWeight = FontWeights.Bold;
txtBlock2.Foreground = new SolidColorBrush(Colors.Green);
txtBlock2.VerticalAlignment = VerticalAlignment.Top;
Grid.SetRow(txtBlock2, 0);
Grid.SetColumn(txtBlock2, 1);
//// Add column headers to the Grid
DynamicGrid.Children.Add(txtBlock1);
DynamicGrid.Children.Add(txtBlock2);
RowDefinition gridRow;
TextBlock par;
TextBox amt;
int i = 1;
string pjt = comboBox1.SelectedItem.ToString();
//Display all the Particulars
SqlCeConnection con;
con = dbConnection();
SqlCeCommand cmd;
string sql = "select * from " + pjt;
try
{
cmd = new SqlCeCommand(sql, con);
SqlCeDataReader rdr = cmd.ExecuteReader();
int ordName = rdr.GetOrdinal("Name");
while (rdr.Read())
{
string nam = rdr.GetString(ordName);
gridRow = new RowDefinition();
gridRow.Height = new GridLength(45);
DynamicGrid.RowDefinitions.Add(gridRow);
par = new TextBlock();
par.Text = nam;
par.FontSize = 12;
par.FontWeight = FontWeights.Bold;
Grid.SetRow(par, i);
Grid.SetColumn(par, 0);
amt = new TextBox();
amt.Height = 20;
amt.Width = 190;
amt.Foreground = new SolidColorBrush(Colors.Black);
Grid.SetRow(amt, i);
Grid.SetColumn(amt, 1);
DynamicGrid.Children.Add(par);
DynamicGrid.Children.Add(amt);
i++;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
this.Content = DynamicGrid;
}
I can't figure out why this overlapping occurs.
Please help me out.
I got the solution. I just added code to clear the children, rowDefinition and columndefinition of grid before initializing with values.
Here i the code I used.
grid1.Children.Clear();
grid1.RowDefinitions.Clear();
grid1.ColumnDefinitions.Clear();
//Adding columns to datagrid
ColumnDefinition gridCol1 = new ColumnDefinition();
ColumnDefinition gridCol2 = new ColumnDefinition();
grid1.ColumnDefinitions.Add(gridCol1);
grid1.ColumnDefinitions.Add(gridCol2);
// Add first column header
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = "Particulars";
txtBlock1.FontSize = 14;
txtBlock1.FontWeight = FontWeights.Bold;
txtBlock1.Foreground = new SolidColorBrush(Colors.Green);
txtBlock1.VerticalAlignment = VerticalAlignment.Top;
Grid.SetRow(txtBlock1, 0);
Grid.SetColumn(txtBlock1, 0);
// Add second column header
TextBlock txtBlock2 = new TextBlock();
txtBlock2.Text = "Amount";
txtBlock2.FontSize = 14;
txtBlock2.FontWeight = FontWeights.Bold;
txtBlock2.Foreground = new SolidColorBrush(Colors.Green);
txtBlock2.VerticalAlignment = VerticalAlignment.Top;
Grid.SetRow(txtBlock2, 0);
Grid.SetColumn(txtBlock2, 1);
//// Add column headers to the Grid
grid1.Children.Add(txtBlock1);
grid1.Children.Add(txtBlock2);
RowDefinition gridRow = new RowDefinition();
grid1.RowDefinitions.Add(gridRow);
TextBlock par;
TextBox amt;
int i = 1;
string pjt = comboBox1.SelectedItem.ToString();
//Display all the Particulars
SqlCeConnection con;
con = dbConnection();
SqlCeCommand cmd;
string sql = "select * from " + pjt;
try
{
cmd = new SqlCeCommand(sql, con);
SqlCeDataReader rdr = cmd.ExecuteReader();
int ordName = rdr.GetOrdinal("Name");
while (rdr.Read())
{
string nam = rdr.GetString(ordName);
gridRow = new RowDefinition();
gridRow.Height = new GridLength(45);
grid1.RowDefinitions.Add(gridRow);
par = new TextBlock();
par.Text = nam;
par.FontSize = 12;
par.FontWeight = FontWeights.Bold;
Grid.SetRow(par, i);
Grid.SetColumn(par, 0);
amt = new TextBox();
amt.Height = 20;
amt.Width = 190;
amt.Foreground = new SolidColorBrush(Colors.Black);
Grid.SetRow(amt, i);
Grid.SetColumn(amt, 1);
grid1.Children.Add(par);
grid1.Children.Add(amt);
i++;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
I placed a grid in the XAML file itself instead of creating dynamically. Then added rows and columns dynamically.
Thanks for the help.