Solved

Gridview SelectedIndex is always 0 in SelectedIndexChanged event

Posted on 2011-02-16
3
1,414 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

733 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