简体   繁体   English

在 ASP.NET(C#) 中填充 GridView 的问题

[英]Problem in populating the GridView in ASP.NET(C#)

I'm trying to populate a Gridview with results from loop.我正在尝试用循环的结果填充Gridview But I'm getting only last result in the loop.但我只得到循环中的最后一个结果。
I think GridView is being overwritten on every time the for loop is being executed.我认为每次执行 for 循环时都会覆盖GridView

Can you people help me to remove this problem please.你们能帮我解决这个问题吗?

for (int j = 0; j < i; j++)
{
    Label1.Text += fipath[j];
    Label1.Text += "-------------";
    SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
    SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='" + NAME + "' AND FilePath='" + fipath[j] + "'", conn);

    try
    {
        conn.Open();
        SqlDataReader rdr = comm.ExecuteReader();
        if (Role.Equals("admin"))
        {
            GridView1.DataSource = rdr;
            GridView1.DataBind();
        }
        rdr.Close();
    }
    catch
    {
        conn.Close();
    }
}

There is more than one problem with this code:这段代码存在不止一个问题:

  • seems like if Role== "admin" you don't need to query db at all好像如果Role== "admin"你根本不需要查询 db
  • DataSource of the grid is overridden on every loop iteration, this is why you see only the last value.每次循环迭代都会覆盖网格的DataSource ,这就是为什么您只看到最后一个值的原因。
  • use parameters for SqlCommand to prevent SQL injection.使用SqlCommand的参数来防止 SQL 注入。
  • don't run string concatenation in the loop.不要在循环中运行字符串连接。 Use StringBuilder instead改用StringBuilder
  • use using for your connection.使用using进行连接。 The code is cleaner this way.这样代码更干净。

The fix could look like this:修复可能如下所示:

if (Role != "admin")
    return;

var dataTable = new DataTable();
var stringBuilder = new StringBuilder();
using (var connection = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true"))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = "Select * from FileUpload where UploadedBy = @UploadedBy AND FilePath = @FilePath";
    command.Parameters.AddWithValue("UploadedBy", NAME);
    var filPathParameter = command.Parameters.Add("FilePath", SqlDbType.VarChar);
    for (int j = 0; j < i; j++)
    {
        stringBuilder.Append(fipath[j]);
        stringBuilder.Append("-------------");
        filPathParameter.Value = fipath[j];
        dataTable.Load(command.ExecuteReader(), LoadOption.PreserveChanges);
    }
}
Label1.Text += stringBuilder.ToString();
GridView1.DataSource = dataTable;
GridView1.DataBind();

Also, I don't know how many elements your normal loop is.另外,我不知道您的正常循环有多少元素。 If it is one or two and you have appropriate indexes in FileUpload table then it is ok to leave as is.如果它是一两个,并且您在FileUpload表中有适当的索引,那么可以保持原样。 However, if you need to do the for many times you should consider switching to a single query instead但是,如果您需要多次执行,则应考虑切换到单个查询

For example:例如:

var filePathes = string.Join(",", fipath.Select(arg => "'" + arg + "'"));
var command = "Select * from FileUpload where UploadedBy = @UploadedBy AND FilePath in (" + filePathes + ")";

This query is SQL injection prone.这个查询是 SQL 注入倾向。 And has a 2100 elements limit in MS SQL.并且在 MS SQL 中有 2100 个元素的限制。

There is more than one way to approach this.有不止一种方法可以解决这个问题。 Depends on your DBMS and requirements.取决于您的 DBMS 和要求。

Use the in clause in SQL Query and pass the list of ID's in FilePath使用 SQL 中的in子句查询并传递 FilePath 中的 ID 列表

SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='" + NAME 
 + "' AND FilePath in (" + listOfIDs + ")", conn);

Check out these URLs that are related to the use of in clause.查看这些与in子句的使用相关的 URL。

Techniques for In-Clause and SQL Server In-Clause 和 SQL 服务器的技术

Parameterizing a SQL IN clause? 参数化 SQL IN 子句?

Create a list or BindingSource outside the loop, bind that to your gridview and then add all records to that list or source.在循环外创建一个列表或 BindingSource,将其绑定到您的 gridview,然后将所有记录添加到该列表或源中。

The problem with your current approach is that you are overwriting the records pulled from the database with a new datasource each time, so as you stated, only the last one is "set", and the older assignments are disposed of.您当前方法的问题是您每次都用新的数据源覆盖从数据库中提取的记录,因此正如您所说,只有最后一个是“设置”的,并且旧的分配被处理掉了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM