开发者

changing order of boundfield in gridview

开发者 https://www.devze.com 2023-04-11 18:56 出处:网络
iam trying to develop one application, the data displayed in Gridview. gridview contains many boundfield colums . I recently add a column after the end of last boundfield column of gridview (Imported

i am trying to develop one application, the data displayed in Gridview. gridview contains many boundfield colums . I recently add a column after the end of last boundfield column of gridview (Imported boundfield column). so i have less chance to move the last boundfield to desired location in mark up. if i move the column to desired place, then i've to modify entire coding while row _databounding. so is there any way we can re order the columns without changing in mark up ?? ..

<asp:BoundField DataField="someData" HeaderText="SomeData"> </asp:BoundField>
 <asp:CommandField UpdateText="Update" EditText="Edit" CancelText="|Cancel" ShowEditButton="true" ControlStyle-CssClass="LinkNormal" />
 <asp:BoundField DataField="someData2" HeaderText="Imported"> </asp:BoundField> 

out put will be like this (EDit/Delete/Imported are boundfield columns )

SomeData | Update| Imported

what i need now gridview shoud display like this

Importe开发者_运维知识库d | SomeData | Update


I would suggest moving away from using column indexes, and start using data keys to reference column values in the code-behind. That way, you can change the markup and move columns around without effecting the code-behind.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Col1, Col2, Col3" ... >

Using data keys, you can get column values like this in the RowDataBound event:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string col1 = GridView1.DataKeys[e.Row.RowIndex]["Col1"].ToString();
}


It seems, that GridView hasn't such functionailty. Instead of, you can try to obtain indexes of columns in code behind by for example column's header text, below is such function that does the job:

int getColumnIndexByHeaderText(GridView gridView, string headerText)
{
    for (int i = 0; i < gridView.Columns.Count; ++i)
    {
        if (gridView.Columns[i].HeaderText == headerText)
            return i;
    }
    return -1;
}

And use it instead of hardcoded column indexes.

0

精彩评论

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