按下按钮时显示网格中的详细信息

时间:2015-01-12 07:34:04

标签: c# asp.net gridview

我有一个Gridview,其中包含人员的详细信息, 我还有一个文本框和搜索按钮,当我输入特定人的名字时 它应该显示自己的细节以及thr网格视图中的标题。

这是我的代码..

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=ENTERKEY001;Initial Catalog=ThirdJanuaryDb;Integrated Security=True");//DataBase Connection

        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "SearchSp";
        cmd.Parameters.Add("@NAME", SqlDbType.VarChar).Value = TextBox4.Text.Trim();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        GridView1.DataBind();
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();      
}

请帮助我...

2 个答案:

答案 0 :(得分:0)

我看到一些错误。

  • 绑定gridview后,使用ExecuteNonQuery执行查询。实际上,你根本没有绑定任何东西。而且您不需要ExecuteNonQuery,因为我认为您的存储过程会返回一些数据,而不仅仅是执行。
  • 使用ExecuteReader获取所有值并将其分配给DataSource属性。

SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataValueField = "someColumn";
GridView1.DataTextField = "someColumn";
GridView1.DataBind();
  • 使用using statement处理您的SqlConnectionSqlCommandSqlDataReader作为最佳做法。

using(SqlConnection con = new SqlConnection(CnnStr))
using(SqlCommand cmd = con.CreateCommand())
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "SearchSp";
    cmd.Parameters.Add("@NAME", SqlDbType.VarChar).Value = TextBox4.Text.Trim();
    using(SqlDataReader dr = cmd.ExecuteReader())
    {
       GridView1.DataSource = dr;
       GridView1.DataBind();
    }
}

答案 1 :(得分:0)

你不应该使用数据适配器,但这里是固定代码,它应该像这样工作:

SqlConnection con = new SqlConnection(@"Data Source=ENTERKEY001;Initial Catalog=ThirdJanuaryDb;Integrated Security=True");//DataBase Connection
        con.Open();
        try
        {
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "SearchSp";
            cmd.Parameters.AddWithValue("@NAME", TextBox4.Text.Trim());
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        finally
        {
            con.Close();
        }
相关问题