I am having a schedule print from a database and using a loop. I have done this in asp but I am changing to c# asp.net and having troubles.
First I print the schedule headers
time|court|court|court
based on the number of courts then it prints the games.
Next ff the current records date is different the last date it will print the date over the entire table row.
Then it checks to see if the time is of the current record is the same as the last if it is not it prints the time and then the game record if it is it just prints the game record.
My problem is I am declaring the TableRow in the time if statment so when I try to use it in another statment it is out of scope. If I take the tablerow outside of the if statement it doesn't print right.
Here is what I have.
for (int i = 0; i < GameCount; i++)
{
DateTime currentdatetime = (DateTime)Schedules.Tables["Schedule"].Rows[i]["datetime"];
string ndate = currentdatetime.ToString("MM/dd/yyy");
string ntime = currentdatetime.ToString("HH:mm");
string nextdate = currentdatetime.ToString("MM/dd/yyy");
if (i + 1 != GameCount)
{
DateTime nextdatetime = (DateTime)Schedules.Tables["Schedule"].Rows[i + 1]["datetime"];
nextdate = nextdatetime.ToString("MM/dd/yyy");
}
string TeamA = Schedules.Tables["Schedule"].Rows[i]["teamA"].ToString();
string TeamB = Schedules.Tables["Schedule"].Rows[i]["teamB"].ToString();
//check to see if date is current
if (LastDate != ndate)
{
TableRow daterow = new TableRow();
TableCell datecell = new TableCell();
datecell.ColumnSpan = 7;
datecell.Controls.Add(new LiteralControl(ndate));
daterow.Cells.Add(datecell);
ScheduleTable.Rows.Add(daterow);
LastDate = ndate;
}
//print the games
if (currentdatetime != LastDateTime)
{
TableRow gamerow = new TableRow();
TableCell timecell = new TableCell();
timecell.Controls.Add(new LiteralControl(ntime));
gamerow.Cells.Add(timecell);
if (i + 1 != GameCount & ndate != nextdate)
{
ScheduleTable.Rows.Add(gamerow);
}
}//check to see if next game is part of the current row
else
{
TableCell gamecell = new TableCell();
gamecell.Controls.Add(new LiteralControl(TeamA + ".vs." + TeamB));
gamerow.Cells.Add(gamecell);
}
}
I can also post what I currently have in asp if that would help... you can go to www.swgc.ca/volleyball/2011/schedules.asp to see what I am trying to accomplish.
Thanks
Change your last bit to:
TableRow gamerow = new TableRow();
if (currentdatetime != LastDateTime)
{
TableCell timecell = new TableCell();
timecell.Controls.Add(new LiteralControl(ntime));
gamerow.Cells.Add(timecell);
}//check to see if next game is part of the current row
else
{
TableCell gamecell = new TableCell();
gamecell.Controls.Add(new LiteralControl(TeamA + ".vs." + TeamB));
gamerow.Cells.Add(gamecell);
}
if (i + 1 != GameCount & ndate != nextdate)
{
ScheduleTable.Rows.Add(gamerow);
}
And I'd strongly recommend looking at gridviews and repeater/list controls, as this is what they are for.
The easiest solution would be to pull your instantiation outside of the for loop. Try this (untested code):
TableRow gamerow = new TableRow();
TableCell timecell = new TableCell();
TableCell gamecell = new TableCell();
TableRow daterow = new TableRow();
TableCell datecell = new TableCell();
for (int i = 0; i < GameCount; i++)
{
DateTime currentdatetime = (DateTime)Schedules.Tables["Schedule"].Rows[i]["datetime"];
string ndate = currentdatetime.ToString("MM/dd/yyy");
string ntime = currentdatetime.ToString("HH:mm");
string nextdate = currentdatetime.ToString("MM/dd/yyy");
if (i + 1 != GameCount)
{
DateTime nextdatetime = (DateTime)Schedules.Tables["Schedule"].Rows[i + 1]["datetime"];
nextdate = nextdatetime.ToString("MM/dd/yyy");
}
string TeamA = Schedules.Tables["Schedule"].Rows[i]["teamA"].ToString();
string TeamB = Schedules.Tables["Schedule"].Rows[i]["teamB"].ToString();
//check to see if date is current
if (LastDate != ndate)
{
daterow = new TableRow();
datecell = new TableCell();
datecell.ColumnSpan = 7;
datecell.Controls.Add(new LiteralControl(ndate));
daterow.Cells.Add(datecell);
ScheduleTable.Rows.Add(daterow);
LastDate = ndate;
}
//print the games
if (currentdatetime != LastDateTime)
{
gamerow = new TableRow();
timecell = new TableCell();
timecell.Controls.Add(new LiteralControl(ntime));
gamerow.Cells.Add(timecell);
if (i + 1 != GameCount & ndate != nextdate)
{
ScheduleTable.Rows.Add(gamerow);
}
}//check to see if next game is part of the current row
else
{
gamecell = new TableCell();
gamecell.Controls.Add(new LiteralControl(TeamA + ".vs." + TeamB));
gamerow.Cells.Add(gamecell);
}
This is a non-optimized answer for your question. I feel like there is probably a better OO way to achieve your goal, but didn't want to answer a question you didn't ask.
Related
I am trying to make a timetable using a .txt file as a source, but I am having some trouble. I am creating a website, using C# and ASP.NET.
And this is what I get:
I tried so hard to put all the data in the same 5 rows, but it's just seems impossible, they always hop to the different rows. Just to make things clear, this is my expectation:
Just in case, this is the code I wrote, maybe I messed up somewhere:
string[] allLines = File.ReadAllLines(Server.MapPath("App_Data/Classes.txt"))
foreach(string line in allLines){
string[] parts = line.Split(',');
TableRow row = new TableRow();
TableCell number = new TableCell();
TableCell lesson = new TableCell();
TableCell number2 = new TableCell();
TableCell lesson2 = new TableCell();
TableCell number3 = new TableCell();
TableCell lesson3 = new TableCell();
TableCell number4 = new TableCell();
TableCell lesson4 = new TableCell();
TableCell number5 = new TableCell();
TableCell lesson5 = new TableCell();
if (parts[1] == "Monday" & parts[0] == "5a klase")
{
number.Text = parts[2];
lesson.Text = parts[3];
}
if (parts[1] == "Tuesday" & parts[0] == "5a klase")
{
number2.Text = parts[2];
lesson2.Text = parts[3];
}
if (parts[1] == "Wednesday" & parts[0] == "5a klase")
{
number3.Text = parts[2];
lesson3.Text = parts[3];
}
if (parts[1] == "Thursday" & parts[0] == "5a klase")
{
number4.Text = parts[2];
lesson4.Text = parts[3];
}
if (parts[1] == "Friday" & parts[0] == "5a klase")
{
number5.Text = parts[2];
lesson5.Text = parts[3];
}
row.Cells.Add(number);
row.Cells.Add(lesson);
row.Cells.Add(number2);
row.Cells.Add(lesson2);
row.Cells.Add(number3);
row.Cells.Add(lesson3);
row.Cells.Add(number4);
row.Cells.Add(lesson4);
row.Cells.Add(number5);
row.Cells.Add(lesson5);
Table1.Rows.Add(row);
}
Any help is much appreciated!
P.S. Here's how the .txt file looks like (ignore the non-English names, those are school subjects in Lithuanian):
So here's something to start from. I just freehanded it, so I'm sure there's syntax and other errors in there, but try it, change your own code, etc
public class DoWork(){
var scheduleEntries = new List<ScheduleEntry>();
File.ReadAllLines(Server.MapPath("App_Data/Classes.txt")).Select(i=>scheduleEntries.Add(new ScheduleEntry(i)));
var maxRowCount = scheduleEntries.Max(i=>i.Ordinal);
for (int k = 1; k <= maxRowCount; k++){
var tableRow = new TableRow;
// Monday
var mondayCellItem = scheduleEntries.FirstOrDefault(i=>i.Ordinal == k && i.Day == "Monday")
var mondayCell = new TableCell{
Text = $"{mondayCellItem.Class}"
// Tuesday, etc
tableRow.Cells.Add(mondayCell);
tableRow.Cells.Add(tuesdayCell);
//etc
}
}
internal class ScheduleEntry(){
public string Day {get;set;}
public int Ordinal {get;set;}
public string ClassName {get;set;}
public ScheduleEntry(string inRow){
var values = inRow.Split(',');
Day = values[1]; // should do some validation here
Ordinal = int.Parse(values[2]); // and here
ClassName = values[3]; // and here
}
}
}
You can use Linq to split the text file into rows which are already split by the comma. Then it's just a matter of looping all the items. It all works dynamically so you can add as much weekdays and rows per weekday as needed.
//create a list with the rows already split by comma
List<string[]> allRows = File.ReadLines(Server.MapPath("/textfile1.txt")).Select(line => line.Split(',')).ToList();
//group by weekday
var sortedList = allRows.GroupBy(x => x[1]).ToList();
//get the max number of rows needed
var rowCount = sortedList.Max(x => x.Count()) + 1;
//create a new table
Table table = new Table();
//fill the table with rows and columns
for (int i = 0; i < rowCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < (sortedList.Count * 2); j++)
{
//if it is the first row add the row headers
if (i == 0)
{
row.BackColor = Color.LightGray;
if (j % 2 == 1)
row.Cells.Add(new TableCell() { Text = sortedList[j /2].Key });
else
row.Cells.Add(new TableCell() { Text = "Nr" });
}
else
{
row.Cells.Add(new TableCell());
}
}
table.Rows.Add(row);
}
//loop all the weekdays
for (int i = 0; i < sortedList.Count; i++)
{
int j = 1;
//loop all the items within a weekday
foreach (var item in sortedList[i])
{
//the item[x] is based on the sample txt file, it is the row split by comma index
table.Rows[j].Cells[i * 2].Text = item[2];
table.Rows[j].Cells[(i * 2) + 1].Text = item[3];
j++;
}
}
I have been searching quite a bit, but unable to find something that addresses the issue I am seeing. I am sure I am missing something simple, but I have been fighting it too long, and really need to figure out what is going on. I have an existing (working) user control that I am rebuilding. It is a multi-step wizard, with each step being a type of "form" created from tables. I have successfully converted 3 of the 4 steps to divs to make them dynamic (using Bootstrap 3), but this one step, step 2, is not working like the rest. The user's input is being lost. The original code (table based) works properly. It is a simple table declared on the .ascx side:
<asp:WizardStep ID="childInformationStep" runat="server" Title="">
<%-- Some more stuff...--%>
<asp:Table cellpadding="2" class="annualSurveyTable" cellspacing="0" border="0" ID="tblChildInfo" runat="server">
</asp:Table>
<asp:WizardStep>
On the c# side, during Page_Load, a method is called to cycle through all the children of a family and dynamically build rows with pre-populated input cells for each child's First/Last Name, B-day, gender and grade. It looks like this:
private void AddChildEdit(Person child, int index)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
row.ID = "trChildFirstName_" + index;
cell.ID = "tcChildFirstName_" + index;
cell.VerticalAlign = VerticalAlign.Middle;
cell.HorizontalAlign = HorizontalAlign.Right;
cell.Wrap = false;
cell.CssClass = "registrationLabel";
cell.Text = "Child's First Name";
row.Cells.Add(cell);
cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "tbChildFirstName_" + index;
tb.Text = child.FirstName;
tb.Enabled = false;
cell.Controls.Add(tb);
row.Cells.Add(cell);
tblChildInfo.Rows.AddAt(tblChildInfo.Rows.Count, row);
// snip (more of same for last name)
row = new TableRow();
cell = new TableCell();
row.ID = "trChildBirthday_" + index;
cell.ID = "tcChildBirthday_" + index;
cell.VerticalAlign = VerticalAlign.Middle;
cell.HorizontalAlign = HorizontalAlign.Right;
cell.Wrap = false;
cell.CssClass = "registrationLabel Birthday";
cell.Text = "Child's Birth Date";
row.Cells.Add(cell);
cell = new TableCell();
DateTextBox dtb = new DateTextBox();
dtb.ID = "tbChildBirthday_" + index;
dtb.CssClass = "registrationItem Birthday";
if (child.BirthDate != DateTime.MinValue && child.BirthDate != DateTime.Parse("1/1/1900"))
dtb.Text = child.BirthDate.ToShortDateString();
cell.Controls.Add(dtb);
row.Cells.Add(cell);
tblChildInfo.Rows.AddAt(tblChildInfo.Rows.Count, row);
row = new TableRow();
cell = new TableCell();
row.ID = "trChildGender_" + index;
cell.ID = "tcChildGender_" + index;
cell.VerticalAlign = VerticalAlign.Middle;
cell.HorizontalAlign = HorizontalAlign.Right;
cell.Wrap = false;
cell.CssClass = "registrationLabel";
cell.Text = "Child's Gender";
row.Cells.Add(cell);
cell = new TableCell();
DropDownList ddlGender = new DropDownList();
ListItem l = new ListItem("", "", true);
l.Selected = true;
ddlGender.Items.Add(l);
l = new ListItem("Male", "0", true);
ddlGender.Items.Add(l);
l = new ListItem("Female", "1", true);
ddlGender.Items.Add(l);
ddlGender.ID = "ddlChildGender_" + index;
// snip (there is one more row added for grade
}
And the save method looks like it cycles through the table looking for the inputs related to the children it is looping through, and pulling in the text value, which should include any changes the user has made. It works as desired, and looks like this (BTW, I didn't write it, it looks like it could be cleaned up quite a bit :D)
private void SaveChildValues()
{
string userID = CurrentUser.Identity.Name + " - Annual Survey";
if (userID == " - Annual Survey")
userID = "Annual Survey";
int i = 0;
foreach (Person child in childrenList)
{
TableCell selectedCell = null;
foreach (TableRow row in tblChildInfo.Rows)
{
if (row.ID == "trChildBirthday_" + i)
{
foreach (TableCell cell in row.Cells)
{
if (cell.ID == "tcChildBirthday_" + i)
{
selectedCell = cell;
DateTextBox box = (DateTextBox)selectedCell.FindControl("tbChildBirthday_" + i);
if (box.Text.Trim() != string.Empty)
try { child.BirthDate = DateTime.Parse(box.Text); }
catch { }
i++;
break;
}
}
break;
}
}
}
i = 0;
foreach (Person child in childrenList)
{
TableCell selectedCell = null;
foreach (TableRow row in tblChildInfo.Rows)
{
if (row.ID == "trChildGender_" + i)
{
foreach (TableCell cell in row.Cells)
{
if (cell.ID == "tcChildGender_" + i)
{
selectedCell = cell;
DropDownList ddl = (DropDownList)selectedCell.FindControl("ddlChildGender_" + i);
if (ddl.SelectedValue != string.Empty)
try { child.Gender = (Gender)Enum.Parse(typeof(Gender), ddl.SelectedValue); }
catch { }
i++;
break;
}
}
break;
}
}
}
i = 0;
foreach (Person child in childrenList)
{
TableCell selectedCell = null;
foreach (TableRow row in tblChildInfo.Rows)
{
if (row.ID == "trChildGrade_" + i)
{
foreach (TableCell cell in row.Cells)
{
if (cell.ID == "tcChildGrade_" + i)
{
selectedCell = cell;
DropDownList ddl = (DropDownList)selectedCell.FindControl("ddlChildGrade_" + i);
if (ddl.SelectedValue != string.Empty)
try { child.GraduationDate = Person.CalculateGraduationYear(Int32.Parse(ddl.SelectedValue), CurrentOrganization.GradePromotionDate); }
catch { }
i++;
break;
}
}
break;
}
}
}
}
Now, here are the changes that I have made to that section. The page loads, and runs through all the motions, yet when the save happens, it is pulling in the original DB value from the child record again instead of the user's input. I simply changed the table to an ASP Panel in the .ascx file:
<asp:WizardStep ID="childInformationStep" runat="server" Title="">
<%-- Some more stuff...--%>
<asp:Panel ID="tblChildInfo" runat="server" ClientIDMode="Static">
</asp:Panel>
<asp:WizardStep>
I have changed the dynamic row creation to dynamic divs, laid out for bootstrap 3:
private void AddChildEdit(Person child, int index)
{
Panel childRow = new Panel();
childRow.ID = "ChildRow_" + index;
childRow.CssClass = "form-horizontal";
LiteralControl childTitle = new LiteralControl();
childTitle.Text = string.Format("<h4>Child {0}:</h4>", (index + 1).ToString());
childRow.Controls.Add(childTitle);
Panel formGroup = new Panel();
formGroup.ID = "trChildFirstName_" + index;
formGroup.CssClass = "form-group";
childRow.Controls.Add(formGroup);
Panel inputContainer = new Panel();
inputContainer.CssClass = "col-sm-8";
formGroup.Controls.Add(inputContainer);
TextBox tb = new TextBox();
tb.ID = "tbChildFirstName_" + index;
tb.Text = child.FirstName;
tb.Enabled = false;
inputContainer.Controls.Add(tb);
Label inputLabel = new Label();
inputLabel.ID = "tcChildFirstName_" + index;
inputLabel.CssClass = "col-sm-3 control-label registrationLabel";
inputLabel.Text = "First Name";
inputLabel.AssociatedControlID = tb.ID;
formGroup.Controls.AddAt(0, inputLabel);
tblChildInfo.Controls.Add(childRow);
// snip (more code for adding Last Name row
formGroup = new Panel();
formGroup.ID = "trChildBirthday_" + index;
formGroup.CssClass = "form-group";
inputContainer = new Panel();
inputContainer.ID = "tcChildBirthday_" + index;
inputContainer.CssClass = "col-sm-8";
formGroup.Controls.Add(inputContainer);
TextBox dtb = new TextBox();
dtb.ID = "tbChildBirthday_" + index;
dtb.CssClass = "form-control survey-control date-mask registrationItem";
dtb.Attributes.Add("placeholder", "MM/DD/YYYY");
if (child.BirthDate != DateTime.MinValue && child.BirthDate != DateTime.Parse("1/1/1900"))
dtb.Text = child.BirthDate.ToString("MM/dd/yyyy");
inputContainer.Controls.Add(dtb);
inputLabel = new Label();
inputLabel.CssClass = "col-sm-3 control-label";
inputLabel.Text = "BirthDate";
inputLabel.AssociatedControlID = dtb.ID;
formGroup.Controls.AddAt(0, inputLabel);
childRow.Controls.Add(formGroup);
// snip (more of the same, adding two more rows for gender and grade)
}
And I simplified the save method to:
private void SaveChildValues()
{
string userID = CurrentUser.Identity.Name + " - Annual Survey";
if (userID == " - Annual Survey")
userID = "Annual Survey";
int i = 0;
foreach (Person child in childrenList)
{
try
{
TextBox box = (TextBox)tblChildInfo.FindControl("tbChildBirthday_" + i);
if (box.Text.Trim() != string.Empty)
child.BirthDate = DateTime.Parse(box.Text);
}
catch { }
try
{
DropDownList ddl = (DropDownList)tblChildInfo.FindControl("ddlChildGender_" + i);
if (ddl.SelectedValue != string.Empty)
child.Gender = (Gender)Enum.Parse(typeof(Gender), ddl.SelectedValue);
}
catch {}
try
{
DropDownList ddl = (DropDownList)tblChildInfo.FindControl("ddlChildGrade_" + i);
if (ddl.SelectedValue != string.Empty)
child.GraduationDate = Person.CalculateGraduationYear(Int32.Parse(ddl.SelectedValue), CurrentOrganization.GradePromotionDate);
}
catch { }
i++;
}
As far as I understand it, my code does not change any fundamental behavior, other than it is using div elements to build out the dynamic content rather then adding rows to a table. What am I missing that is causing my updated code to lose the users' input?
NOTE: this is step two, where the information is rendered, captured for the child info. The save method is not executed until step 4, so the input data should be persisting through two more steps, and remain in tact. I have tried using debugger, but can never see the users input. I don't know if I am looking for it at the wrong breakpoints, but I can't seem to find where the user input is coming back with the post, and when it SHOULD be getting written to the inputs. Any help would be greatly appreciated.
You could try moving the dynamic creation of the fields into the Page_Init section rather than the Page_Load.
I have two functions. In my first i have created the TextBox:
private TableRow GetGebuchteDienstleistungRow(Dienstleistungsreservierung dr, int rowIndex)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
if (dr.Dienstleistung.Mengeneinheit == Mengeneinheit.Basket)
{
foreach (Basketdienstleistung basketDl in dr.Dienstleistung.Basket)
{
cell = new TableCell();
cell.Text = "<tr />";
row.Cells.Add(cell);
TableRenderer.AddTableCell(row, dr.Von.ToString(form.DatumsFormat), 1);
TableRenderer.AddTableCell(row, dr.Von.ToString(form.ZeitFormat), 1);
TableRenderer.AddTableCell(row, dr.Bis.ToString(form.DatumsFormat), 1);
TableRenderer.AddTableCell(row, dr.Bis.ToString(form.ZeitFormat), 1);
cell = new TableCell();
var txt = new TextBox();
txt.Text = string.Format("{0:0.00}", dr.Bestellmenge * basketDl.Anzahl);
txt.Width = 42;
txt.MaxLength = 5;
txt.CssClass = "nummer";
cell.Controls.Add(txt);
row.Cells.Add(cell);
................
}
}
}
.................
How can i get the value of the created TextBox in my second function? Specifically I want to pass the value in a database.
You can use FindControl method
var textBox = (TextBox)cell.FindControl("YourID");
You can enumerate through all controls in specific cell and find your textbox by name
cell.Controls.OfType<TextBox>();
I have this data in same sql table. I need to create a tree look like structure for the following data. Everything seems to be working fine except the indenting is not working right. I am missing something minor which I am not able to figure out. I will appreciate any help.
This is data in same table
initiated_by
---------------------
NULL,42521,42521,41651,41111,41111,41131,41651
user_id (assigned to)
---------------------
42521,41651,42681,41111,42021,41131,42001,43001
What I expecting is as follow.
42521 (at level 0)
41651 (at level 1)
41111 (at level 2)
42021(at level 3)
41131(at level 3)
42001(at level 4)
43001(at level 2)
42681 (at level 1)
But what I am getting is not right. I am not able to figure out the indentLevel part. indentLevel is a variable declared at class level.
private void BuildTable(DataTable recordList)
{
foreach (DataRow dr in recordList.Rows)
{
TableRow tblRow = new TableRow();
TableCell tblCell = new TableCell();
tblCell.Controls.Add(GetDetailTable(dr, indentLevel));
tblCell.HorizontalAlign = HorizontalAlign.Left;
tblRow.Cells.Add(tblCell);
mainTable.Rows.Add(tblRow);
//Do we have any child objects
int cId = Convert.ToInt32(dr["user_id"].ToString());
DataTable dt = GetChildObjects(Convert.ToInt32(dr["user_id"].ToString()), masterDT);
if (dt.Rows.Count > 0) indentLevel = indentLevel+1; BuildTable(dt);
}
}
private Table GetDetailTable(DataRow dr, int indentLevel)
{
Table DetailTable = new Table();
DetailTable.Width = Unit.Percentage(100);
DetailTable.CssClass = "SortableTable";
TableRow tblRow = new TableRow();
TableCell tblEmptyCell = new TableCell();
tblEmptyCell.Width = Unit.Percentage(5);
tblEmptyCell.Controls.Add(new LiteralControl(string.Empty));
tblEmptyCell.Width = Unit.Percentage(5 * indentLevel);
tblRow.Cells.Add(tblEmptyCell);
//To Display Name
TableCell tblCell = new TableCell();
tblCell.Width = Unit.Percentage(15);
tblCell.CssClass = "alt-row-hover";
LiteralControl lc = new LiteralControl(dr["user_id"].ToString());
tblCell.Controls.Add(lc);
tblCell.HorizontalAlign = HorizontalAlign.Left;
tblRow.Cells.Add(tblCell);
mainTable.Rows.Add(tblRow);
//To Display Detials
TableCell tblCellDetials = new TableCell();
tblCellDetials.CssClass = "alt-row";
tblCellDetials.Width = Unit.Percentage(80);
StringBuilder detailString = new StringBuilder();
detailString.Append("Action: " + Convert.ToString(dr["action_id"]) + "<br>");
detailString.Append("Action Date: " + Convert.ToString(dr["action_date"]) + "<br>");
detailString.Append("Comments: " + Convert.ToString(dr["comments"]) + "<br>");
LiteralControl lcd = new LiteralControl(detailString.ToString());
tblCellDetials.Controls.Add(lcd);
tblCellDetials.HorizontalAlign = HorizontalAlign.Left;
tblRow.Cells.Add(tblCellDetials);
DetailTable.Rows.Add(tblRow);
return DetailTable;
}
}
You don't have anything which decrements indentLevel at the end of BuildTable.
Personally, I would change BuildTable to take the indentLevel as well, and just change this:
if (dt.Rows.Count > 0) indentLevel = indentLevel+1; BuildTable(dt);
to this:
if (dt.Rows.Count > 0)
{
BuildTable(dt, indentLevel + 1);
}
Then just call it initially with:
BuildTable(rootTable, 0);
... and remove the instance variable completely. That way you don't need to decrement indentLevel at all; each nested call will just naturally get the right level.
By the way, C# isn't line-based when it comes to blocks - so currently your code is equivalent to:
// Current code
if (dt.Rows.Count > 0)
{
indentLevel = indentLevel + 1;
}
BuildTable(dt, indentLevel);
That won't actually do any harm in this particular case, as the method does nothing when dt.Rows is empty, but it means your code is somewhat confusing. Personally I prefer to always use braces.
I have an asp.net table control like this:
TableHeader
A Text | Textbox
What I want to do is, in the page_load event, duplicate second row with all the controls within it, change the text in the first cell and add as a new row. So here is my code:
for (int i = 0; i < loop1counter; i++)
{
TableRow row = new TableRow();
row = myTable.Rows[1]; //Duplicate original row
char c = (char)(66 + i);
if (c != 'M')
{
row.Cells[0].Text = c.ToString();
myTable.Rows.Add(row);
}
}
But when I execute this code it justs overwrites on the original row and row count of the table doesn't change. Thanks for help....
As thekip mentioned, you are re-writing the reference.
Create a new row. Add it to the grid and then copy the cell values in whatever manner you want.
Something like:
TableRow tRow = new TableRow();
myTable.Rows.Add(tRow);
foreach (TableCell cell in myTable.Rows[1].Cells)
{
TableCell tCell = new TableCell();
tCell.Text = cell.Text;
tRow.Cells.Add(tCell);
}
It gets overwritten because you overwrite the reference. You don't do a copy, essentially the row = new TableRow() is doing nothing.
You should use
myTable.ImportRow(myTable.Rows[1]).
Adjusted based on response try:
row = myTable.Rows[1].MemberwiseClone();
so try this
private TableRow CopyTableRow(TableRow row)
{
TableRow newRow = new TableRow();
foreach (TableCell cell in row.Cells)
{
TableCell tempCell = new TableCell();
foreach (Control ctrl in cell.Controls)
{
tempCell.Controls.Add(ctrl);
}
tempCell.Text = cell.Text;
newRow.Cells.Add(tempCell);
}
return newRow;
}
your code:
for (int i = 0; i < loop1counter; i++)
{
TableRow row = CopyTableRow(myTable.Rows[1]); //Duplicate original row
char c = (char)(66 + i);
if (c != 'M')
{
row.Cells[0].Text = c.ToString();
myTable.Rows.Add(row);
}
}