Selecteddatakey始终为null asp.net gridview

时间:2013-04-28 14:16:09

标签: c# asp.net gridview null

我使用填充在另一个数据网格视图的rowcommand事件上的gridview

问题是,当我尝试在selectedchanged事件上使用selecteddatakey属性时,它总是给我错误

  

对象引用未设置为对象的实例

cmd1.Parameters.AddWithValue("@busid", GridView2.SelectedDataKey.Value.ToString());

我运行调试,发现selecteddatakey为null

下面是我用来填充gridview的代码

SqlDataSource2.ConnectionString = "Data Source=localhost;Initial Catalog=WCA Database;Integrated Security=True";
                SqlDataSource2.SelectCommand = "FindAvaliableBuses";
                SqlDataSource2.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
                SqlDataSource2.DataBind();

                int index = Convert.ToInt32(e.CommandArgument);
                string Startdate = GridView1.Rows[index].Cells[3].Text;
                string DueDate = GridView1.Rows[index].Cells[4].Text;
                SqlDataSource2.SelectParameters.Add("startdate", Startdate);
                SqlDataSource2.SelectParameters.Add("duedate", DueDate);
                SqlDataSource2.SelectParameters.Add("branchId", "11");
                GridView2.DataSource = SqlDataSource2;
                GridView2.DataBind();
                GridView2.DataKeyNames = new string[] {"BusId"};
                Label1.Text = index.ToString();

这是我用来选择的代码:

protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection con1 = new SqlConnection("Data Source=localhost;Initial Catalog=WCA Database;Integrated Security=True");
    con1.Open();
    SqlCommand cmd1 = new SqlCommand("insert BusAcivity (BusId, ActivityId) values(@busid, @activityid)", con1);
    cmd1.Parameters.AddWithValue("@busid", GridView2.SelectedDataKey.Value.ToString());
    cmd1.Parameters.AddWithValue("@activityid", Label1.Text);
    cmd1.ExecuteNonQuery();
}

0 个答案:

没有答案