views:

880

answers:

1

Can anyone give me a short snippet that, given a GridView that was originally bound to a simple string array, and given a GridViewRow row, will return the value that was bound to the row?

+2  A: 

You can't, the only property System.String has is Length, and DataKeyName expects a property of the object you are binding to. To answer your second question, here is an example of getting the string value from a GridViewRow.

In your ASPX file:

<asp:GridView ID="GridView1" runat="server"
    OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="String Value">
            <ItemTemplate>
                <%# Container.DataItem %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In your codebehind:

protected void Page_Load(object sender, EventArgs e) {
    string[] arrayOfStrings = new string[] { "first", "second", "third" };
    GridView1.DataSource = arrayOfStrings;
    GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
    if (e.Row.RowType == DataControlRowType.DataRow) {
        // e.Row is of type GridViewRow
        // e.Row.DataItem contains the original value that was bound,
        // but it is of type object so you'll need to cast it to a string.
        string value = (string)e.Row.DataItem;
    }
}

The only reasonable workaround to the problem is to either create a wrapper class that has properties. Or if you are using .NET 3.5, you can use LINQ to make a temporary list which only includes your value as a property of the class. There is an example of this technique on MSDN Forums by vtcoder.

List<string> names = new List<string>(new string[] { "John", "Frank", "Bob" });

var bindableNames = from name in names
                    select new {Names=name};

GridView1.DataSource = bindableNames.ToList();

Then "Name" would be the DataKeyName and BoundField DataField.

DavGarcia