Search code examples
c#asp.netgridviewselectedvalueselectedindexchanged

All GridView rows disappear while selecting a row


Please consider the values in comments which I got in debug mode:

protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
    int selected = FilesGrid.SelectedIndex; // selected = 2
    FilesGrid.DataBind();  //added after feedback in comments. it makes no change
    int count = FilesGrid.Rows.Count; // count = 0
    GridViewRow row = FilesGrid.Rows[selected]; // row = null
    GridViewRow row0 = FilesGrid.Rows[0]; // row = null
}

I came to this code while investigating why SelectedValue gives null in this event handler (the DataKeyNames parameter was set for sure).

Can anybody explain how it is possible?

Thank you in advance.

PS. Here is my aspx code:

<asp:GridView ID="FilesGrid" runat="server" AutoGenerateColumns="False" 
    AutoGenerateSelectButton="True"  
    onselectedindexchanged="FilesGrid_SelectedIndexChanged" 
    style="margin-top: 0px" >
    <Columns>
        <asp:CommandField ShowDeleteButton="True" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Length" DataFormatString="{0:N0}" 
            HeaderText="Size in Bytes" HtmlEncode="False" />
    </Columns>
</asp:GridView>

Here is how I bind data:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string [] dd = {"FullName"};
        FilesGrid.DataKeyNames = dd;

        string appPath = Request.PhysicalApplicationPath; 
        DirectoryInfo dirInfo = new DirectoryInfo(appPath); 
        FileInfo[] files = dirInfo.GetFiles();
        FilesGrid.DataSource = files;
        FilesGrid.DataBind();            } 
}

Solution

  • The issue was resolved by commenting out the line // if (!Page.IsPostBack). It looks like the data source is lost somehow during the postback. The whole seems to be a local bug with ViewState, because this behavior was not observed by other users. My special thanks to Tim Schmelter and naveen.