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>();
Related
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'm dynamically adding the rows and columns to a Table, but i am unable to adjust the first column's width.. i tried all possible combinations of "Unit" (new Unit(300, Unit Type.Point) ) - but no joy. It always shows the column-width to length of the data in that column, but i wanted it to be fixed. what's wrong here please.
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tc = new TableCell();
tc.ID = "tcResource";
tc.Text = "Resource_Name";
Unit uWidth = new Unit(300, UnitType.Point);
tc.Width = uWidth;
tr.Cells.Add(tc);
for (i = 1; i <= 365; i++)
{
tc = new TableCell();
tc.ID = "tc" + i.ToString();
tc.Text = dtStart.AddDays(i).ToString("dd/MM") ;
dtRange[i - 1] = dtStart.AddDays(i );
tr.Cells.Add(tc);
}
tHoliday.Rows.Add(tr);
Try this
Unit width = new Unit(30, UnitType.Pixel);
TableCell cell = new TableCell();
cell.Width = width;
You should be adjusting the columns width with a CSS style, not by doing it server side. Put this in a CSS file:
td.tcResouce{ width:300px }
and add a link in your ASP.Net page:
<link rel="stylesheet" type="text/css" href="/path/to/file.css">
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.
I know what my fault is, but not sure how to resolve. I am trying to generate an asp:table from Code Behind.
The table should be 3 cells wide... I'll work on the row limit later.
Here's my code:
GallaryImage g = new GallaryImage();
var images = g.GetAll();
photos.Style.Add("width","100%");
photos.Style.Add("border-style","none");
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tr.Cells.Add(tc);
tr.Cells.Add(tc);
tr.Cells.Add(tc);
int cntr = 0;
TableRow row = new TableRow();
foreach (var image in images)
{
cntr++;
TableCell cell = new TableCell();
Image i = new Image();
i.ImageUrl = image.fullThumbPath;
cell.Controls.Add(i);
row.Cells.Add(cell);
if(cntr%3==0)
{
photos.Rows.Add(row);
row.Cells.Clear();
}
}
if(row.Cells.Count > 0)
photos.Rows.Add(row);
}
My problem is that I need to create a new row in the Foreach, only when I need the new row... i.e, when we have added 3 cells.
I thought I could add the row to the table, and then clear the row to start a new row - but that's not working, as I just keep clearing the same row object... and therefore, never add multiple rows.
Can someone assist with my logic here?
GallaryImage g = new GallaryImage();
var images = g.GetAll();
photos.Style.Add("width","100%");
photos.Style.Add("border-style","none");
int cntr = 0;
TableRow row = new TableRow();
foreach (var image in images)
{
cntr++;
TableCell cell = new TableCell();
Image i = new Image();
i.ImageUrl = image.fullThumbPath;
cell.Controls.Add(i);
row.Cells.Add(cell);
if(cntr%3==0)
{
photos.Rows.Add(row);
row = new TableRow();
}
}
if(row.Cells.Count > 0)
photos.Rows.Add(row);
}
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);
}
}