i have a customized gridview.my grid is able to sort for each column just by 1 click in the heade开发者_Go百科r without any setting and overloading methods such as sorting,etc by user(programmer).(i do this successfully and work fine) users(programmers) maybe add each column in grid.such as template field,hyperlinkfield,boundfield... . for sorting, i must access datafield of columns. i can access boundfield column by this code.i can access datafield and header text and ... sample:
for (int j = 0; j < this.Columns.Count; j++)
{
BoundField bf;
bf = this.Columns[j] as BoundField;
if (bf != null)
{
string ht = bf.HeaderText;
string df = bf.DataField;
}
}
but i can access control in the templateField.such as ColumnBound. sample:
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
i want access "Name" (Bind ("Name") or Eval ("Name")) . how can i? there is a point: i dont now what is the ID (in this case "Label1") of control in templatefield. special thanks
Sorting on template field may not be feasible - template field may have been bound with multiple data fields and determining correct sort fields is difficult.
If you take some constrained view such as only those template fields can be sorted where label and/or anchor is bound to some data field then approach would be
- See if column is template field (
var tf = this.Columns[j] as TemplateField
) - If yes, take the template (use
ItemTemplate
property) - Iterate recursively via children controls of the template, if you find the label (or say anchor) then inspect its text property for data binding expression and to get your data field.
But this approach will fail for template such as <img src="Some Icon" /><span><%# Eval("Name") %></span>
.
Another variation of above technique would be to take item template of field and then invoke Render
method to get template html and then you can parse it to search data bind expressions and then to decide your data fields. However, this approach has it own pitfalls - for example, template such as <img src='<%# Eval("IconType") %>' /><span><%# Eval("Name") %></span>
will probably make above logic to sort by IconType field instead of Name field.
IMO, more robust approach will be to have property/method in your gridview control that will accept sort fields (if any) for template columns.
精彩评论