动态地向ASP.NET中的Gridview添加行(C#)

时间:2011-06-16 07:43:08

标签: c# asp.net gridview templatefield

        <asp:GridView ID="GridView1" runat="server">
        <Columns>
            <asp:TemplateField HeaderText="FileName">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="" Text=""></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
     </Columns>
    </asp:GridView>


aspx.cs文件

    SqlCommand comm = new SqlCommand(Select 
        FileUpload.FileName AS FileName,
        FileUpload.FilePath AS PATH,
        SubjectMaster.SubjectName AS Subject,
        MemberPersonalInformation.FirstName As SharedBy 
    from FileUpload",conn)

我需要在网格中打印FileName(As Hyperlink)SharedBySubject我该怎么办?
我需要做这样的事情......但是下面的方法不起作用

        conn.Open();
        SqlDataReader rdr = comm.ExecuteReader();

        int i = 0;
        while (rdr.Read())
        {

            string fip = rdr["PATH"].ToString();
           HyperLink h1 = (HyperLink)GridView1.Rows[i].Cells[0].FindControl("Hyperlink1");
                h1.Text = rdr["FileName"].ToString();
                h1.NavigateUrl = "download.aspx?filepath=" + fip;

                GridView1.Rows[i].Cells[1].Text = rdr["SharedBy"].ToString();
                GridView1.Rows[i].Cells[2].Text = rdr["Subject"].ToString();
                GridView1.Rows[i].Cells[3].Text = rdr["PATH"].ToString();
                //GridView1.Rows[i].Rows.Add(di);

              i++;

        }

1 个答案:

答案 0 :(得分:0)

试试这个:

<asp:GridView ID="GridView1" runat="server">
  <Columns>
    <asp:TemplateField HeaderText="FileName">
      <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("PATH")%>' Text='<%#Eval("FileName")%>'></asp:HyperLink>,
        <asp:Literal ID="Literal1" runat="server" Text='<%#Eval("SharedBy")+", "+ Eval("Subject")%>' />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
/asp:GridView>

在cs中,您可以使用以下查询绑定网格视图:

conn.Open();
SqlCommand comm = new SqlCommand("your query");
SqlDataReader rdr = comm.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = rdr;
GridView1.DataBind();
rdr.close();