Reputation: 65
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.
Upvotes: 0
Views: 2773
Reputation: 65
So, to change the position of any column in the GridView i had to bound fields to my data source.
Upvotes: 0
Reputation: 716
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;
}
Upvotes: 1
Reputation: 13484
Try this.Use insert
for dynamically created columns
devicesTable.Columns.Insert(0, buttonField)
DataGridViewColumnCollection.Insert Method
Upvotes: 1