Solved

Gridview SelectedIndex is always 0 in SelectedIndexChanged event

Posted on 2011-02-16
3
1,402 Views
Last Modified: 2012-05-11
I have a major problem with urgent needed solution.
Since today the method was running perfect, now, after selecting a gridview row, the total gridview row count is 0, regardless of what row I select (in debug mode the "tp" value is 0). Because of that the following error is thrown:
dViewSearchResult.Rows[selectedRow]      'GridViewSearchResult.Rows[selectedRow]' threw an exception of type 'System.ArgumentOutOfRangeException'      System.Web.UI.WebControls.GridViewRow {System.ArgumentOutOfRangeException}

  Don't know if it is a VStudio 2008 issue. pls help me with a valid solution.
Thanks!
<asp:GridView 
                ID="GridViewSearchResult" runat="server" AllowPaging="True" PageSize="30" 
                OnSelectedIndexChanged="GridViewSearchResult_SelectedIndexChanged" 
                OnPageIndexChanging="GridViewSearchResult_PageIndexChanging"
                AutoGenerateColumns="false">   

protected void GridViewSearchResult_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selectedRow = (int)GridViewSearchResult.SelectedIndex;
        GridView selectionGridView= (GridView)Master.FindControl("SelectionGridView");
        DataTable dt = new DataSet1.SelectionDataTableDataTable();
        //DataTable dt = new DataTable();        
        try
        {
            DataTable dttemp = (DataTable)Session["SelectedTable"];
            if (dttemp.Rows.Count > 0)
            {
                dt = (DataTable)Session["SelectedTable"];
            }
            DataRow newrow = dt.NewRow();

            //!!!searches must be made by datafieldname, not header text!
            int tp = GridViewSearchResult.Rows.Count;
            int custidindex = PublicClass.FormatDataGridView.getColumnIndex(GridViewSearchResult.Rows[selectedRow], "Customer_Id");

namespace PublicClass
 public static class FormatDataGridView
{
public static int getColumnIndex(GridViewRow row, string SearchColumnName)
        {
            int index=0;
            foreach (DataControlFieldCell cell in row.Cells)
            {
                if (cell.ContainingField is BoundField)
                {
                    string tmp = ((BoundField)cell.ContainingField).DataField.ToString();
                    if (((BoundField)cell.ContainingField).DataField.Equals(SearchColumnName))
                   {
                       break;
                   }
                }
                index++;
            }
            return index;
        }
    }

Open in new window

0
Comment
Question by:danielivanov2
  • 2
3 Comments
 
LVL 8

Accepted Solution

by:
TheMozz earned 300 total points
ID: 34907376
Are you binding the grid in Page_Load? If so, make sure you wrap the call to bind the grid inside a

if(!Page.IsPostBack) block, otherwise the grid will rebind on each load of the page - including when the user chooses a row, thus clearing the selected row.
0
 

Author Comment

by:danielivanov2
ID: 34907681
no, its bound inside a button click event, practivally the gridview is the result of a customer search
in this stage, the data is bound ok, but in selectedindexchanged event the gridview shows Rows.Count=0 (in code)

 
protected void ButtonSearch_Click(object sender, EventArgs e)
{DataTable dtResult = new DataTable();
                SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["pricingtoolsConnectionString"].ToString());
                using (sqlConn)
                {
                    using (SqlCommand cmd = new SqlCommand("prc_SearchCustomer"))
                    {
                        SqlDataAdapter da = new SqlDataAdapter();
                        cmd.Connection = sqlConn;
                        da.SelectCommand = cmd;
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@SearchCriteria", searchListBox.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@SearchString", searchTextBox.Text);
                        cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
                        sqlConn.Open();
                        cmd.ExecuteReader();
                        sqlConn.Close();
                        da.Fill(dtResult);
                    }
                }
                Session["SearchResult"] = dtResult;
                GridViewSearchResult.DataSource = dtResult;
                GridViewSearchResult.DataBind();
}

Open in new window

0
 

Author Closing Comment

by:danielivanov2
ID: 34909632
finally I have found the problem
you were right, I was binding it also in Page_Load:
if (Session["SearchResult"]!=null)
            if (Session["SearchResult"] != "")
                ResultsGridView.DataSource = (DataTable)Session["SearchResult"];                
            else
                ResultsGridView.DataSource = null;  
        ResultsGridView.DataBind();

Meanwhile I had modified the script to
if (Session["SearchResult"]!=null)
            if (Session["SearchResult"][b].ToString()[/b] != "")
                GridViewSearchResult.DataSource = (DataTable)Session["SearchResult"];                
            else
                GridViewSearchResult.DataSource = null;  
        GridViewSearchResult.DataBind();
and that conversion to ToString() was the problem
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to prevent website from publishing with errors 9 53
Creating a route in asp.net webforms 2 32
How to create an MVC5, Razor Widget 2 26
asp enable view state 1 28
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question