How to use a DataAdapter with stored procedure and parameter

前端 未结 9 733
名媛妹妹
名媛妹妹 2020-11-30 01:05

I want to fill a DataGridView control using DataAdapter. But I don\'t know how to do it since I\'m using a stored procedure with parameter. Can someone cite an example pleas

相关标签:
9条回答
  • 2020-11-30 01:55
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = <sql server name>;
            builder.UserID = <user id>; //User id used to login into SQL
            builder.Password = <password>; //password used to login into SQL
            builder.InitialCatalog = <database name>; //Name of Database
    
            DataTable orderTable = new DataTable();
    
            //<sp name> stored procedute name which you want to exceute
            using (var con = new SqlConnection(builder.ConnectionString))
            using (SqlCommand cmd = new SqlCommand(<sp name>, con)) 
            using (var da = new SqlDataAdapter(cmd))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                //Data adapter(da) fills the data retuned from stored procedure 
               //into orderTable
                da.Fill(orderTable);
            }
    
    0 讨论(0)
  • 2020-11-30 02:00

    Maybe your code is missing this line from the Microsoft example:

    MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
    
    0 讨论(0)
  • 2020-11-30 02:00
    public class SQLCon
    {
      public static string cs = 
       ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlDataAdapter MyDataAdapter;
        SQLCon cs = new SQLCon();
        DataSet RsUser = new DataSet();
        RsUser = new DataSet();
        using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
           {
            MyConnection.Open();
            MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
            //'Set the command type as StoredProcedure.
            MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
            RsUser = new DataSet();
            MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
            SqlDbType.Int));
            MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
            MyDataAdapter.Fill(RsUser, "GetAPPID");
           }
    
          if (RsUser.Tables[0].Rows.Count > 0) //data was found
          {
            Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
           }
         else
           {
    
           }    
    }    
    
    0 讨论(0)
提交回复
热议问题