1

我想GridView用 aHyperLink和其他两个字段填充。

我半心半意地尝试了以下方法。它给出了错误。

SqlCommand comm = new SqlCommand(
    @"Select 
        FileUpload.FileName AS FileName,
        FileUpload.FilePath AS PATH,
        SubjectMaster.SubjectName AS Subject,
        MemberPersonalInformation.FirstName As SharedBy 
    from FileUpload 
    INNER JOIN ContentManagement 
        ON ContentManagement.FileId=FileUpload.FileId  
    INNER JOIN MemberPersonalInformation 
        ON MemberPersonalInformation.MemberId=ContentManagement.CreatedBy 
    INNER JOIN SubjectMaster 
        ON ContentManagement.SubjectName=SubjectMaster.SubjectId  
    where 
        FileUpload.FileId in
        (
            Select FileId 
            from ContentManagement 
            where 
                ContentId in
                (
                    Select ContentId 
                    from ContentToIndividual 
                    where ShowToMemberId=@MemberId
                ) and 
                ContentManagement.ContentTypeId=@TPD and
                ContentManagement.SessionId=@SessionId
        )", conn);

      conn.Open();
        SqlDataReader rdr = comm.ExecuteReader();
        int i = 0;
        while (rdr.Read())
        {
            string fip = rdr["PATH"].ToString();
            GridViewRow di = GridView1.Rows[i];

                HyperLink h1 = (HyperLink)di.FindControl("Hyperlink1");
                h1.Text = rdr["FileName"].ToString();
                h1.NavigateUrl = "download.aspx?filepath=" + fip;

                di.Cells[1].Text = rdr["SharedBy"].ToString();
                di.Cells[2].Text = rdr["Subject"].ToString();

                i++;

        }
        rdr.Close();

获取错误消息

指数超出范围。必须是非负数且小于集合的大小。
参数名称:索引

如果有人建议我更好的方法来做到这一点或纠正这个错误,请。

4

4 回答 4

1

确保您的 gridview 至少有三,否则此行将引发您描述的异常:

di.Cells[2].Text = rdr["SharedBy"].ToString();

另一方面,您需要小心这一行:

 h1.NavigateUrl = "download.aspx?filepath=" + fip;

将路径传递给客户端然后传回服务器是引入安全问题的好方法,请确保 download.aspx 检查文件路径参数是否指向真正应该可下载的文件!:)

于 2011-06-16T06:42:02.900 回答
1

GridView.Rows集合索引是从零开始的。您需要i初始化。

i变量的值超过集合中的可用索引时,就会发生错误GridView.Rows因此,如果用零初始化i变量不能解决问题,则返回的结果集(由阅读器读取)具有比集合更多的项目。GridView.Rows

要确保i变量的值不超过GridView.Rows集合的可用索引,请使用以下命令:

while (rdr.Read() && i < gridView.Rows.Count)

如果您需要向您添加行,GridView则使用以下命令:

while (rdr.Read() && i < 3)
{
    string fip = rdr["PATH"].ToString();
    GridViewRow di = new GridViewRow();

    ....

    gridView.Rows.Add(di);        
    i++;        
}

另一个原因可能是您用来引用GridViewRow.Cells.

于 2011-06-16T06:15:34.140 回答
0

设置 int i = 0; 并检查,索引从 0 开始而不是 1

于 2011-06-16T06:17:17.180 回答
0

我认为您的读者收藏计数与网格行计数的大小不匹配,这就是它给出“索引超出范围”的原因检查此进行检查

if(GridView1.Rows.Count  > i)

然后在这个你想要的表演之后

于 2011-06-16T06:48:56.487 回答