c#asp.net表的行总是在同一行中

本文关键字:一行 net c#asp | 更新日期: 2023-09-27 18:19:42

我有这个代码

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);
    }
}

出于某种原因,该表只显示了从文档中读取的最后一行,我不知道它为什么这么做。

有人有主意吗?

c#asp.net表的行总是在同一行中

您不会在每次迭代中创建新行。而是更新现有行。

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 );
}

您的表总是使用相同的行和单元格对象,您需要在循环中创建新对象:

id=new TableCell();等等…