c# asp.net table row always going in the same row - c#

I have this code
protected void Page_Load(object sender, EventArgs e)
{
TblPrikaz.BorderWidth = 1;
XmlDocument baza = new XmlDocument();
XmlTextReader reader = new XmlTextReader(Server.MapPath("baza.xml"));
baza.Load(reader);
TableRow line = new TableRow();
TableCell id = new TableCell();
TableCell ime = new TableCell();
TableCell prezime = new TableCell();
TableCell godiste = new TableCell();
id.Text = "ID";
ime.Text = "Ime";
prezime.Text = "Prezime";
godiste.Text = "Godiste";
line.BackColor = Color.Green;
line.Cells.Add(id);
line.Cells.Add(ime);
line.Cells.Add(prezime);
line.Cells.Add(godiste);
TblPrikaz.Rows.Add(line);
XmlNodeList popis = baza.GetElementsByTagName("element");
for (int i = 0; i < popis.Count; i++)
{
if (string.Compare(popis[i].Attributes["ID"].Value.ToString(), "0") == 0) continue;
id.Text = popis[i].Attributes["ID"].Value.ToString();
ime.Text = popis[i].ChildNodes[0].InnerText;
prezime.Text = popis[i].ChildNodes[1].InnerText;
godiste.Text = popis[i].ChildNodes[2].InnerText;
line.Cells.Add(id);
line.Cells.Add(ime);
line.Cells.Add(prezime);
line.Cells.Add(godiste);
TblPrikaz.Rows[i].Cells.Add(id);
TblPrikaz.Rows[i].Cells.Add(ime);
TblPrikaz.Rows[i].Cells.Add(prezime);
TblPrikaz.Rows[i].Cells.Add(godiste);
}
}
for some reason, the table only shows the loast row read fromthe document and I have no idea why it is doing that.
Anyone have an idea?

You are not creating a new row on each iteration. Instead, you are updating the existing row.
XmlNodeList popis = baza.GetElementsByTagName( "element" );
for ( int i = 0; i < popis.Count; i++ )
{
var element = popis[i];
if ( element == null || element.Attributes == null )
continue;
if ( element.Attributes["ID"].Value.ToString() == "0" )
continue;
var idCell = new TableCell { Text = element.Attributes["ID"].Value.ToString() };
var imeCell = new TableCell { Text = element.ChildNodes[0].InnerText };
var prezimeCell = new TableCell { Text = element.ChildNodes[1].InnerText };
var godisteCell = new TableCell { Text = element.ChildNodes[2].InnerText };
var row = new TableRow();
row.Cells.Add( idCell );
row.Cells.Add( imeCell );
row.Cells.Add( prezimeCell );
row.Cells.Add( godisteCell );
TblPrikaz.Rows.Add( row );
}

Your table always use the same row and cell objects, you need to create new ones in the loop:
id = new TableCell();
etc....

Related

Dynamically Created TextBox AutoPostBack on TextChanged but Event Function is not called

everybody,
I have been trying for days now to solve this problem with no success.
I have textboxes in table cells which are created dynamically upon button click. Three of these buttons will take a value, calculation method (% or Const Value) and the value to apply respectively. Below is the function which creates these TB's among other controls.
protected void btnAddService_Click(object sender, EventArgs e)
{
TableRow r = new TableRow();
TableCell c0 = new TableCell();
TableCell c1 = new TableCell();
TableCell c2 = new TableCell();
TableCell c3 = new TableCell();
TableCell c4 = new TableCell();
TableCell c5 = new TableCell(); // Management Fees (% or Const)
TableCell c6 = new TableCell(); // Management Fees Value
TableCell c7 = new TableCell(); // Remarks
service s = new service();
if (serCount == 0)
{
tblHeader.Visible = true;
}
// Add the Services DropDownList...
DropDownList ddlS = new DropDownList();
ddlS.ID = "ddlServices" + serCount;
ddlS.Items.Add("Management");
ddlS.Items.Add("MEP");
ddlS.Items.Add("Landscaping");
ddlS.Items.Add("Pest Control");
ddlServices.Add(ddlS);
ddlS.CssClass = "form-control";
ddlS.Width = Unit.Percentage(100);
c0.Controls.Add(ddlS);
c0.Width = Unit.Percentage(15);
s.serviceName = "Management";
// Add Subcontracted Checkbox...
CheckBox chkSubCont = new CheckBox();
chkSubCont.ID = "chkSubCont" + serCount;
chkSubContracted.Add(chkSubCont);
c1.Controls.Add(chkSubCont);
c1.Width = Unit.Percentage(5);
c1.HorizontalAlign = HorizontalAlign.Center;
s.subcontracted = false;
// Add Subcontracted Value...
TextBox txtSubContVal = new TextBox();
txtSubContVal.ID = "txtSubcontractVal" + serCount;
txtSubContVal.CssClass = "form-control";
txtSubContVal.Attributes.Add("placeholder", "0.000");
txtSubContVal.Style.Add("text-align", "right");
txtSubcontValue.Add(txtSubContVal);
c2.Controls.Add(txtSubContVal);
c2.Width = Unit.Percentage(10);
s.subcontValue = 0;
// Add Management Fees Type (% or Const)...
DropDownList ddlMFT = new DropDownList();
ddlMFT.Items.Add("%");
ddlMFT.Items.Add("Value");
ddlMFT.CssClass = "form-control";
ddlMFT.Width = Unit.Percentage(100);
ddlMFT.ID = "ddlManFeesType" + serCount;
ddlManFeesType.Add(ddlMFT);
c5.Controls.Add(ddlMFT);
c5.Width = Unit.Percentage(5);
// Add Management Fees Value...
TextBox txtMFVal = new TextBox();
txtMFVal.CssClass = "form-control";
txtMFVal.Attributes.Add("placeholder", "0.000");
txtMFVal.Style.Add("text-align", "right");
txtMFVal.Width = Unit.Percentage(100);
// txtMFVal.ID = "txtManFeesValue" + serCount;
txtMFVal.AutoPostBack = true;
txtMFVal.TextChanged += new EventHandler(txtManFeesVal_TextChange);
txtManFeesValue.Add(txtMFVal);
c6.Controls.Add(txtMFVal);
c6.Width = Unit.Percentage(10);
// Add Manpower Value...
TextBox txtManp = new TextBox();
txtManp.ID = "txtManpower" + serCount;
txtManp.CssClass = "form-control";
txtManp.Attributes.Add("placeholder", "0");
txtManp.Style.Add("text-align", "center");
txtManPower.Add(txtManp);
c3.Controls.Add(txtManp);
c3.Width = Unit.Percentage(10);
s.manPower = 0;
// Add Quoted Value...
TextBox txtQuotVal = new TextBox();
txtQuotVal.ID = "txtQuotedValue" + serCount;
txtQuotVal.CssClass += "form-control";
// txtQuotVal.Text = "0.000";
txtQuotVal.Attributes.Add("placeholder", "0.000");
txtQuotVal.Style.Add("text-align", "right");
txtQuotVal.AutoPostBack = true;
txtQuotVal.ClientIDMode = ClientIDMode.Static;
txtQuotVal.TextChanged += (o, ep) => {
TextBox t = sender as TextBox;
if (t.Text == "")
{
t.Text = "0.000";
}
txtPrjValue.Text = (int.Parse(txtPrjValue.Text) + int.Parse(t.Text)).ToString();
};
txtQuotValue.Add(txtQuotVal);
c4.Controls.Add(txtQuotVal);
c4.Width = Unit.Percentage(10);
// Add Remarks Box...
TextBox txtRem = new TextBox();
txtRem.ID = "txtRemarks" + serCount;
txtRem.CssClass += "form-control";
txtRem.ClientIDMode = ClientIDMode.Static;
txtRem.Width = Unit.Percentage(100);
txtRemarks.Add(txtRem);
c7.Controls.Add(txtRem);
c7.Width = Unit.Percentage(35);
s.quotedValue = 0;
// Add the cells to the new row...
r.Cells.Add(c0);
r.Cells.Add(c1);
r.Cells.Add(c2);
r.Cells.Add(c5);
r.Cells.Add(c6);
r.Cells.Add(c3);
r.Cells.Add(c4);
r.Cells.Add(c7);
// Add the new row...
tblServices.Rows.Add(r);
serCount++;
// Postback to refresh contents from Server Side...
string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}
Upon TextChanged of txtMFVal text, it does PostBack but it doesn't call the attached event handler, shown below:
protected void txtManFeesVal_TextChange(object sender, EventArgs e)
{
TextBox txtMFV = sender as TextBox;
// Get the parent cell of the TextBox...
TableRow tr = txtMFV.Parent.Parent as TableRow;
TextBox txtSCV = tr.Cells[2].Controls[0] as TextBox;
TextBox txtMFT = tr.Cells[5].Controls[0] as TextBox;
double scv = Double.Parse(txtSCV.Text);
double mfv = Double.Parse(txtMFV.Text);
double v = 0;
if (txtMFT.Text == "%")
{
v = (scv * mfv) / 100;
}
else
{
v = scv + mfv;
}
TextBox txtQP = tr.Cells[6].Controls[0] as TextBox;
txtQP.Text = v.ToString();
// Postback to refresh contents from Server Side...
string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}
I have tried so many tricks I have found on the net and all didn't work.
Please, help.
Thanks,

Add Required Validator on Dynamic Asp:net Table

I want to add some Required Validator on Controls(Textbox as example) in a dynamic asp:table.
Code:
foreach (KeyValuePair<string, string> o in Collection)
{
TableRow Row = new TableRow();
TableCell valueCell = new TableCell();
TableCell Cell = new TableCell();
TextBox txtBox = new TextBox();
TextBox txtBox1 = new TextBox();
txtBox1.ID = o.Key + o.Value;
if (o.Value.Contains("Mandatory"))
{
RequiredFieldValidator req = new RequiredFieldValidator();
req.ErrorMessage = "Required";
req.BorderColor = System.Drawing.Color.Red;
req.ControlToValidate = txtBox1.ID;
req.Enabled = true;
req.Display = ValidatorDisplay.Dynamic;
Cell.Controls.Add(req);
}
valueCell.Controls.Add(txtBox1);
Row.Cells.Add(valueCell);
Row.Cells.Add(Cell);
table.Rows.Add(Row);
}
But i am getting this error:
" System.Web.UnhandledException in System.web.dll"
on the line Row.Cells.Add(Cell);
Can you help me ?
I fix the problem with a Panel which contains the Texbox and the RequireValidatorField.
Panel p = new Panel();
p.Controls.Add(txtBox1);
p.Controls.Add(req);
valueCell.Controls.Add(p);

Use dynamic table to display list of string

I tried to display the list of time slots by using dynamic table in C#. However, it does not work properly. Here is my result:
And here is my code
List<AvailableTime> AllTimeSlots = RequestDirector.ListAllAvailableTimes(BookingDate);
foreach (AvailableTime resultTimeslot in AllTimeSlots)
{
TableRow TimeSLotRow = new TableRow();
TableCell TimeSlotCell = new TableCell();
TimeSlotCell.Text = Convert.ToString(resultTimeslot.TimeSlot);
TimeSLotRow.Cells.Add(TimeSlotCell);
Table1.Rows.Add(TimeSLotRow);
}
I want to display 5 time slots each row. Can anybody tell me how I can do that?
Probably something like this :
int i = 0;
TableRow TimeSLotRow = new TableRow();
foreach (AvailableTime resultTimeslot in AllTimeSlots)
{
TableCell TimeSlotCell = new TableCell();
TimeSlotCell.Text = Convert.ToString(resultTimeslot.TimeSlot);
TimeSLotRow.Cells.Add(TimeSlotCell);
i++;
if(i == 5)
{
Table1.Rows.Add(TimeSLotRow);
TimeSLotRow = new TableRow();
i = 0;
}
}

Nested lists and foreach loops

I want to add a single row to the table from the two lists. i am getting an error in the second foreach loop. Cannot convert Liability.LiabilityCheckpointInstance to Liability.LiabilityAssignment.
foreach (LiabilityCheckpointInstance ci in value)
{
//foreach (LiabilityAssignment la in value)
//{
var tr = new TableRow();
var tc = new TableCell { Text = ci.CheckGroup };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.IxCheck.ToString() };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.CheckPointInfo.ToString() };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.RejectedBy };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.Role };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.Mistakes.ToString() };
tr.Cells.Add(tc);
//ChkpLiabilityDataTable.Rows.Add(tr);
foreach (LiabilityAssignment la in value )
{
//var tr = new TableRow();
tc = new TableCell { Text = la.LiabileOrganizationName };
tc = new TableCell { Text = la.LiabileOrganizationName };
tr.Cells.Add(tc);
tc = new TableCell { Text = la.LiablePersonName };
tr.Cells.Add(tc);
tc = new TableCell { Text = la.Comment };
tr.Cells.Add(tc);
ChkpLiabilityDataTable.Rows.Add(tr);
}
}
Your foreach loops are:
foreach (LiabilityCheckpointInstance ci in value)
foreach (LiabilityAssignment la in value )
It is looping over the same thing (value) but saying the items in it are different. [1]
I would assume from the context that the second should be looping over ci.something rather than just value.
So you would have:
foreach (LiabilityAssignment la in ci.Something )
Of course you will need to change the Something to whatever your list is.
[1] I should note that the syntax itself is not incorrect. If the items in value is of both types then (eg one is a subtype of the other) it would work fine. This doesn't look like it is the case here though.
This should do the trick for you.
foreach (LiabilityCheckpointInstance ci in value)
{
var tr = new TableRow();
var tc = new TableCell { Text = ci.CheckGroup };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.IxCheck.ToString() };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.CheckPointInfo.ToString() };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.RejectedBy };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.Role };
tr.Cells.Add(tc);
tc = new TableCell { Text = ci.Mistakes.ToString() };
tr.Cells.Add(tc);
// YOU NEED TO BUILD THESE UP FRONT SO YOU CAN LOOP THROUGH THE
// CHILDREN SAFELY BELOW
tr.Cells.Add(new TableCell());
tr.Cells.Add(new TableCell());
tr.Cells.Add(new TableCell());
// I DON'T KNOW IF YOUR PROPERTY IS NAMED LiabilityAssignments OR NOT
// SO REPLACE THAT WITH WHAT EVER IS NECESSARY - BUT IT SHOULD BE THE
// LIST OF LiabilityAssignment ON THE LiabilityCheckpointInstance OBJECT
foreach (LiabilityAssignment la in ci.LiabilityAssignments)
{
tr.Cells[6].Text = la.LiabileOrganizationName;
tr.Cells[7].Text = la.LiablePersonName;
tr.Cells[8].Text = la.Comment;
ChkpLiabilityDataTable.Rows.Add(tr);
}
}
you are using 'value' as the source list for both foreach statements. value apparently contains LiabilityCheckpointInstance objects, so it fails when you try to use it as if it contained LiabilityAssignment objects.
Did you means to sa: foreach (LiabilityAssignment la in ci.)?
Second loop should be
foreach (LiabilityAssignment la in ci)

Ratingcontrol gives Javascript:void(0)

After some minor difficulties with my basic test rating control not working because of the missing inline CSS stylesheet, I am trying to dynamically add a bunch of rating controls in a updatepanel when I click on a button in a different updatepanel. (These panels are both in a parent updatepanel, I have defined the triggers and set the updatemode to conditional). Anyways, when I click the button, he updates the updatepanel with the rating controls, but when I hover over them, he always displays 0 (the current rating), and does not change the rating control star image (filledStarRating). The code relevant to my problem (two methods):
protected void imbformulier_Click(Object sender, ImageClickEventArgs e)
{
imbFormulier.Visible = false;
imbGebruikers.Visible = false;
imbModellen.Visible = false;
pnlGegevens1.Visible = false;
pnlGegevens2.Visible = true;
pnlNavigatie.Visible = true;
pnlEval.Visible = true;
//kijken welk formulier moet ingevuld worden adhv de ddl's en dit meegeven aan de zelfgemaakte klasse
List<EvaluatieFormulier> mijnformulieren = (List<EvaluatieFormulier>)Session["mijnformulieren"];
IEnumerator<EvaluatieFormulier> enumerator = mijnformulieren.GetEnumerator();
EvaluatieFormulier meetegeven = new EvaluatieFormulier();
while (enumerator.MoveNext())
{
if (((enumerator.Current.GebruikergeevalueerdID == ddlGebruikers.SelectedValue) && (enumerator.Current.ModelID == Convert.ToInt32(ddlModellen.SelectedValue))))
{
meetegeven = enumerator.Current;
//Eventueel tekst veranderen als er al was gewerkt aan een bepaalde evaluatie
if (meetegeven.Tijdaangewerkt == 0)
{
lblInfo.Text = "Evaluatie gestart van " + ddlGebruikers.SelectedItem.Text;
lblDatum.Text = "Evaluatie begonnen op: "+ DateTime.Now.Date.ToString("d/M/yyyy") + "(Vandaag)" ;
//updaten in database
Session["aantalminutenaangewerkt"] = 0;
Session["aantalsecondenaangewerkt"] = 0;
timTijdAanGewerkt.Enabled = true;
lblTijd.Visible = true;
}
else
{
lblInfo.Text = "Evaluatie verdergezet van " + ddlGebruikers.SelectedItem.Text;
lblDatum.Text = "Evaluatie laatst gewijzigd : " + meetegeven.Tijdingevuld.ToString();
Session["aantalminutenaangewerkt"] = meetegeven.Tijdaangewerkt;
Session["aantalsecondenaangewerkt"] = 0;
timTijdAanGewerkt.Enabled = true;
lblTijd.Visible = true;
}
}
}
//Rating controls aanmaken voor elke criteria
List<AjaxControlToolkit.Rating> lijstratingcontrols = new List<AjaxControlToolkit.Rating>();
Model modelmetdomeinen = new Model() ;
IEnumerator<Model> modelenum = Database.laadModellenIn().GetEnumerator();
while (modelenum.MoveNext())
{
if (modelenum.Current.ModelID == meetegeven.ModelID)
modelmetdomeinen = modelenum.Current;
}
//foreach (Domein domein in modelmetdomeinen.Domeins)
//{
// foreach (Criterium criterium in domein.Criteriums)
// {
// AjaxControlToolkit.Rating ratingcontrol = new AjaxControlToolkit.Rating();
// ratingcontrol.ID = criterium.CriteriumNaam;
// ratingcontrol.StarCssClass = "ratingStar";
// ratingcontrol.EmptyStarCssClass = "emptyStarRating";
// ratingcontrol.WaitingStarCssClass = "emptyStarRating";
// ratingcontrol.FilledStarCssClass = "filledStarRating";
// ratingcontrol.Changed += new AjaxControlToolkit.RatingEventHandler(rating_Changed);
// ToolkitScriptManager1.RegisterAsyncPostBackControl(ratingcontrol);
// lijstratingcontrols.Add(ratingcontrol);
// }
//}
//Evaluatieform formulier = new Evaluatieform(meetegeven,lijstratingcontrols);
Table evaluatietabel = new Table();
int domeinteller =0;
foreach (Domein domein in modelmetdomeinen.Domeins)
{
domeinteller++;
if (domeinteller < 4)
{
TableRow domeinrij = new TableRow();
TableCell domeintitel = new TableCell();
domeintitel.Text = domeinteller + ". " + domein.DomeinNaam;
domeintitel.BorderStyle = BorderStyle.None;
domeinrij.Cells.Add(domeintitel);
evaluatietabel.Rows.Add(domeinrij);
foreach (Criterium criterium in domein.Criteriums)
{
int criteriumteller = 1;
TableRow criteriumrij = new TableRow();
TableCell criteriumtitel = new TableCell();
TableCell opvulcell = new TableCell();
TableCell ratingcell = new TableCell();
criteriumtitel.BorderStyle = BorderStyle.None;
opvulcell.BorderStyle = BorderStyle.None;
ratingcell.BorderStyle = BorderStyle.None;
criteriumtitel.Text = criteriumteller + ". " + criterium.CriteriumNaam;
AjaxControlToolkit.Rating ratingcontrol = new AjaxControlToolkit.Rating();
ratingcontrol.ID = criterium.CriteriumNaam;
ratingcontrol.StarCssClass = "ratingStar";
ratingcontrol.EmptyStarCssClass = "emptyStarRating";
ratingcontrol.WaitingStarCssClass = "emptyStarRating";
ratingcontrol.FilledStarCssClass = "filledStarRating";
ratingcontrol.Changed += new AjaxControlToolkit.RatingEventHandler(rating_Changed);
ratingcell.Controls.Add(ratingcontrol);
ratingcell.Attributes.Add("runat", "server");
ratingcell.Attributes.Add("onclick", "return false");
criteriumrij.Cells.Add(opvulcell);
criteriumrij.Cells.Add(criteriumtitel);
criteriumrij.Cells.Add(ratingcell);
evaluatietabel.Rows.Add(criteriumrij);
criteriumteller++;
}
}
}
evaluatietabel.BorderStyle = BorderStyle.None;
pnlEval.ContentTemplateContainer.Controls.Add(evaluatietabel);
Session["formulieractief"] = true;
pnlEval.Update();
pnlGegevens1.Update();
pnlGegevens2.Update();
}
I'm also adding the link to an image that shows my problem, so that you can see it for yourself:
We had the same issue recently and the problem was that the latest version of the AjaxControltoolkit seems to require a ToolkitScriptManager instead of the normal ScriptManager.
So just try changing your
asp:ScriptManager tag to
asp:ToolKitScriptManager or
ajax:ToolKitScriptManager
or whatever your namespace is.

Categories

Resources