Solved

Gridview SelectedIndex is always 0 in SelectedIndexChanged event

Posted on 2011-02-16
3
1,375 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
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 …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video discusses moving either the default database or any database to a new volume.

744 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now