Search code examples
c#asp.netgridview

Binding gridview using stored procedure


i have gridview and i used stored procedure in backend . The issue is i have not used any textbox or label only gridview.

When i run my code, It shows a compilation error that spproduct1 expects parameter @id which is expected not supplied. Can you please fix the error

public partial class WebForm1 : System.Web.UI.Page

{

  string _strsql = string.Empty;

  protected void Page_Load(object sender, EventArgs e)

  {

   string cs = ("Data Source=172.16.6.173;Initial Catalog=servion_hari;User  ID=sa;Password=Servion@123");

   _strsql = "select * from tblproduct where id=@id and Name=@Name and  Description=@Description";

    SqlConnection con = new SqlConnection(cs);

    con.Open();

    SqlDataAdapter da = new SqlDataAdapter("spgetproducts1", con);

    SqlCommand cmd = new SqlCommand();

    SqlParameter id = new SqlParameter("@id", SqlDbType.Int.ToString());

    id.Value = GridView1.ToString();


    da.SelectCommand.CommandType = CommandType.StoredProcedure;


     con.Close();

    DataSet ds = new DataSet();

    da.Fill(ds);

    GridView1.DataSource = ds;

     GridView1.DataBind();


        }
    }
}

Solution

  • If you want to add a value to a parameter defined in your query you can use the following:

    cmd.Parameters.AddWithValue("@id", GridView1.ToString());
    

    for a better implementation:

    1. try to put all database related functions in a separate file and call them in your form.
    2. define an stored procedure over your database and call it via C# code. this way of using stored procedure is poor

    Edited

    step1: declare your stored procedure on your database like this:

    CREATE PROCEDURE [dbo].[GET_PRODUCTS_SP]
        /*Type of this variables should be their column types*/
        @id int,
        @name varchar(MAX),
        @description varchar(MAX)
    AS
    BEGIN
        SELECT * FROM [dbo].[tblproduct] 
        WHERE id=@id AND 
              Name=@name AND 
              Description=@description
    END
    

    step 2: call the stored procedure like this:

    DataTable dt = new DataTable();
    String conStr = "Data Source=172.16.6.173;Initial Catalog=servion_hari;User  ID=sa;Password=Servion@123";
    SqlConnection con = new SqlConnection(conStr);
    SqlCommand com = new SqlCommand("GET_PRODUCTS_SP", con);
    com.Parameters.AddWithValue("@id", yourIdValue);
    com.Parameters.AddWithValue("@name", yourNameValue);
    com.Parameters.AddWithValue("@description", yourDescriptionValue);
    com.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter(com);
    try
    {
        con.Open();
        da.Fill(dt);
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        con.Close();
    }
    GridView1.DataSource = dt;
    GridView1.DataBind();