0

How to manipulate GridView2.Columns as BoundField with auto-generate field? Index outof range?GridView2.Columns[6] as BoundField I use Automatic generate field.

JobPostDataContext db = new JobPostDataContext();

        var query = from j in db.JobLists
                    join u in db.UserLists
                        on j.UserID equals u.UserID
                    where j.JobTitle.Contains(this.TextBox1.Text)
                    select new
                    {
                        j.JobID,
                        j.JobTitle,
                        j.Summary,
                        j.Details,
                        j.CompanyName,
                        j.CompanyEmail,
                        j.DatePosted,
                        j.UserID,
                        u.City,
                        u.State,
                        u.Country 
                    };

        GridView2.DataSource = query;
        GridView2.DataBind();
        BoundField DatePosted = GridView2.Columns[6] as BoundField;
        DatePosted.DataFormatString = "{0:MMM,dd yy}";
mike
  • 1
  • 1
  • Since GridView.Columns is a Collection, you can check it's .Count property. How many Columns does it think it has? – Ken White Mar 14 '11 at 00:09
  • but I use auto-generate field. I doubt if there is any Column[index] i can access. I have lots of column just want to manipulate one of them,so i keep the auto-generate option. Can i override just 1 column with Boundfield coding? – mike Mar 14 '11 at 00:21
  • As soon as you bind the data, the columns are generated. At that point, there's a Columns.Count (and a Columns[Index]). *Before* you try to execute `GridView2.Columns[6] as BoundField;`, check the Columns.Count. – Ken White Mar 14 '11 at 00:40
  • it is "0" with GridView1.Columns.Count.ToString(), Then how can i access inside 0 with sub-column 6. Again,because i use auto-generate field – mike Mar 14 '11 at 00:47
  • even I tried GridView2.Columns[0] it still pops System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. – mike Mar 14 '11 at 00:57
  • Mike, if it reports 0 columns, you're not getting anything back from your query. You can't access Column[0] even, because there are *no* columns. – Ken White Mar 14 '11 at 01:04

1 Answers1

0

As I mentioned in my comments, you're not getting any results back from your query, and therefore have no (0) columns. That's why you can't access Columns[6].

Columns.Count is returning 0. That's zero columns. You can't access any of them - Columns.Count is 1 based, unlike Columns[Index] which is 0 based. I think that's where you're getting confused.

Ken White
  • 123,280
  • 14
  • 225
  • 444