开发者

gridview.columns how to retrieve it?

开发者 https://www.devze.com 2023-01-04 10:22 出处:网络
Simple thing get a list of columns present in the binded grid view, that\'s it, but gives errors. Try to get the number of columns also does not work! it says zero?

Simple thing get a list of columns present in the binded grid view, that's it, but gives errors.

Try to get the number of columns also does not work! it says zero?

Here's the code:

        try
        {

            commandString = "Select * from Table_1";

            conn = new SqlConnection(Class1.connection);

            command = new SqlCommand(commandString, conn);

            conn.Open();

            reader = command.ExecuteReader();



            GridView1.DataSource开发者_开发知识库 = reader;

            GridView1.DataBind();

           //also not wrking??
            Label1.Text = GridView1.Columns.Count.ToString;


            reader.Close();
            reader.Dispose();

            conn.Close();
            conn.Dispose();

What's wrong? Is there an alternate way to ask grid view for its columns? autogenerate columns is true.


Binding to a reader isn't a very good idea; bind it to a DataTable and see how well that works for you.

I'm not sure how paging would work in the gridview if it's bound to a reader, but just as a best practice your presentation layer shouldn't know anything about your database. By binding your gridview to a reader you have high coupling between layers. Normally you want to return a DataTable or, better yet, a Data Transfer Object (DTO) from a service layer or business layer. I guess if it's a small app where you don't care about scalability then binding to a reader is OK, but personally I would still bind it to a DataTable.

This may help.


This is how I achieved it. If any better coding is possible, please do comment.

int cells_count;
        ArrayList Header_list = new ArrayList();

//wrking..

            cells_count = GridView1.HeaderRow.Cells.Count;

            for (int i = 0; i < cells_count; i++)
            {
                Header_list.Add( GridView1.HeaderRow.Cells[i].Text );
            }
           // Label1.Text = GridView1.HeaderRow.Cells[1].Text;

            //the first colunm name
            Label1.Text = Header_list[0].ToString();
0

精彩评论

暂无评论...
验证码 换一张
取 消