Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
i want to search all the the values of @s below in one text box from one table. so i have created stored procedure for it named as SearchMain, but when i start to run it, it has error on this line comm.Fill(dt);. what would be the best code for this?

What I have tried:

C#
private void button2_Click_2(object sender, EventArgs e)
        {
            con.Open();
            SqlDataAdapter comm = new SqlDataAdapter("SearchMain", con);
            comm.SelectCommand.CommandType = CommandType.StoredProcedure;
            comm.SelectCommand.Parameters.AddWithValue("@date", searchtbx.Text.Trim());
            comm.SelectCommand.Parameters.AddWithValue("@yearlvl", searchtbx.Text.Trim());
            comm.SelectCommand.Parameters.AddWithValue("@complaint", searchtbx.Text.Trim());
            comm.SelectCommand.Parameters.AddWithValue("@medicine", searchtbx.Text.Trim());
            comm.SelectCommand.Parameters.AddWithValue("@fname", searchtbx.Text.Trim());

            DataTable dt = new DataTable();
            dataGridView1.DataSource = dt;
            comm.Fill(dt);
            con.Close(); 

        }
Posted
Updated 16-Mar-21 22:13pm
v2

1 solution

0) Put the code into a try/catch block.
C#
try
{
    con.Open();
    SqlDataAdapter comm = new SqlDataAdapter("SearchMain", con);
    comm.SelectCommand.CommandType = CommandType.StoredProcedure;
    comm.SelectCommand.Parameters.AddWithValue("@date", searchtbx.Text.Trim());
    comm.SelectCommand.Parameters.AddWithValue("@yearlvl", searchtbx.Text.Trim());
    comm.SelectCommand.Parameters.AddWithValue("@complaint", searchtbx.Text.Trim());
    comm.SelectCommand.Parameters.AddWithValue("@medicine", searchtbx.Text.Trim());
    comm.SelectCommand.Parameters.AddWithValue("@fname", searchtbx.Text.Trim());

    DataTable dt = new DataTable();
    dataGridView1.DataSource = dt;
    comm.Fill(dt);
    con.Close();
}
catch (Exception ex)
{
    // put a breakpoint on the curly brace above or below this comment
}


1) USE.THE.DEBUGGER.

2) If you use using statements, you don't have to worry about manually closing the conmection.
C#
SqlConnection con;
SqlAdapter comm;
try
{
    using (con = new SqlConnection(conectionstring))
    {
        con.Open();
        using (comm = new SqlDataAdapter("SearchMain", con))
        {
            //...your code 
        }
    }
}
catch (Exception ex)
{
}


3) Your problem is probably going to be one of these (we don't know which because "has an error" sucks as as problem description:
    a) The connection to the database failed
    b) The stored proc wasn't found
    c) The parameter list is somehow incorrect.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900