0

I am having trouble adding new columns to GridView control from code-behind. I use DataTable as a datasource for my GridView control, and, after binding it, every column that I add to GridView appears at the left side of the control. I need to change it's position.

Please note, that I need to add columns from the code-behind, not from the .aspx file.

My GridView definition in .aspx file:

<asp:GridView ID="devicesTable" runat="server" OnRowEditing="deviceEdit">
</asp:GridView>

And the piece of code, where I try to add a column:

StoredProcedure connection = new StoredProcedure("usp_nsi_mpd_sel");

DataTable dataTable = connection.ExecReader();
ButtonField buttonField = new ButtonField();
buttonField.CommandName = "Select";
buttonField.ButtonType = ButtonType.Button;
buttonField.Text = "Edit";

devicesTable.DataSource = dataTable;
devicesTable.Columns.Add(buttonField);
devicesTable.DataBind();

And this results in buttonField appearing at the left side of the GridView. How do I change it's position?

Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
an40us
  • 65
  • 1
  • 10
  • If the main issue is dynamically changing the order of columns you can see my answer here: http://stackoverflow.com/a/28611217/215752 – Hogan Feb 19 '15 at 16:42

3 Answers3

1

Try this.Use insert for dynamically created columns

devicesTable.Columns.Insert(0, buttonField)

DataGridViewColumnCollection.Insert Method

Nagaraj S
  • 13,316
  • 6
  • 32
  • 53
1

You can use a thing like that,

   private void AdjustColumnOrder()
{
    customersDataGridView.Columns["CustomerID"].Visible = false;
    customersDataGridView.Columns["ContactName"].DisplayIndex = 0;
    customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;
    customersDataGridView.Columns["City"].DisplayIndex = 2;
    customersDataGridView.Columns["Country"].DisplayIndex = 3;
    customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;

}
Julien698
  • 676
  • 3
  • 10
  • 27
  • i can't acces columns by name because i haven't specified them in .aspx page. i found the solution myself, thanks :) – an40us Feb 18 '14 at 11:09
0

So, to change the position of any column in the GridView i had to bound fields to my data source.

an40us
  • 65
  • 1
  • 10