?
Solved

Gridview SelectedIndex is always 0 in SelectedIndexChanged event

Posted on 2011-02-16
3
Medium Priority
?
1,472 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 1200 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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Suggested Courses

800 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