Populate Gridview at runtime using textfile

后端 未结 3 672
忘了有多久
忘了有多久 2021-01-21 08:15

it may seem to be simple problem to many of you, but want i am trying to do is i am reading a text file on a click event using StreamReader (ASP.net & C#) after

3条回答
  •  情话喂你
    2021-01-21 08:54

    1. You should move your code with adding the DataColumn outside the for-loop
    2. You should create new DataRow using DataTable.NewRow method
    3. You should call data binding methods only once, and after the loops.

    Your code should be something like this:

    DataTable dt = new DataTable();
    dt.Columns.Add("Row No", typeof(Int32));
    dt.Columns.Add("Col No", typeof(Int32));
    dt.Columns.Add("Width", typeof(Int32));
    dt.Columns.Add("Height", typeof(Int32));
    dt.Columns.Add("ImageUrl", typeof(String));
    dt.Columns.Add("Description", typeof(String));
    
    using (StreamReader sr = new StreamReader(@"D:\Temp\fileread\readtext.txt"))
    {
        while ((line = sr.ReadLine()) != null)
        {
            string[] parts = line.Split(',');
            var row = dt.NewRow();
            for (int i = 0; i < parts.Length; i++)
            {
                row[i] = parts[i];
            }
            // important thing!
            dt.Rows.Add(row);
        }
        sr.Close();
    }
    MyGridView.DataSource = dt;
    MyGridView.DataBind();
    

提交回复
热议问题