Solved

Gridview SelectedIndex is always 0 in SelectedIndexChanged event

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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

815 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

9 Experts available now in Live!

Get 1:1 Help Now