我在GridView1上面做了“详细信息”的按钮,当用户单击“详细按钮”的时候,就在GridView2里面显示详细的信息,可是当单击“详细信息”的时候出现了错误:
索引超出范围。必须为非负值并小于集合大小。
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _11_4 : System.Web.UI.Page
{
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//获取选择行的编号
string deptID = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
string strsql = "SELECT * FROM tb_Student WHERE ID='" + deptID + "'";
SqlConnection con = GetConnection();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(strsql, con);
DataSet ds = new DataSet();
sda.Fill(ds);
this.GridView2.DataSource = ds;
this.GridView2.DataBind();
}
}
------解决方案--------------------------------------------------------
string deptID = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
判断一下e.NewSelectedIndex的值,检查例外
------解决方案--------------------------------------------------------
GridView1.DataKeys[e.NewSelectedIndex]
这句有问题吧。
在该方法里开头加一句Response.Write(GridView1.DataKeys.Count+"<br/>");
看看是多少,就明白了。
------解决方案--------------------------------------------------------
NewSelectedIndex 没有取到索引吧!
------解决方案--------------------------------------------------------