Home > Net >  My SQL select query code not work properly in C#
My SQL select query code not work properly in C#

Time:08-30

I am new to ASP.net. Try to search the specific row on the base of Primary key which is my StudentInfo. I have try many queries but give me null result when I debug. All other queries like insert, update, Delete work fine except select queries.

This is Search Button code:

protected void Search_Click(object sender, EventArgs e)
        {
      String query = "select * from StudentInfo where StudentId="   int.Parse(Id.Text);
            
            DataTable dt = db.Search(query);
            GridView1.DataSourceID = null;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        } 

This is search function code which I written into class:

public DataTable Search(String query)
        {
            DataTable dt = null;
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(query, conn);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                dt = new DataTable();
                adapter.Fill(dt);
                return dt;
            }
            catch (SqlException e)
            {
                return dt;
            }

I want when I click on search button the matching Id result will show in GridView. But it show nothing although data is present in data base. When I debug it give me null in dataTable:

Can see here after query passing to function result is Null in debuging: image

Same problem in select all data from data base.

I also create a view all record button and want when I click on it all record will show in GridView. But when I click on it give me Null same like upper search result.

This is View all record buttton code:

protected void ViewAll_Click(object sender, EventArgs e)
        {
            String query = "select * from StudentInfo";
            DataTable dt = db.Search(query);
            //GridView1.DataSourceID = null;
            GridView1.DataSource = dt;
            GridView1.DataBind();

        } 

In this I also pass query to search function which code is mention above.

This DataTable result is also same as search query which is null even records is exist in data base.

So what is the mistake which I make??

CodePudding user response:

Check what value is coming in query variable via debugging the code. Also check whether any data exists in the table for your query

CodePudding user response:

        DataTable dt = new DataTable();
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            dt = new DataTable();
            adapter.Fill(dt);
            return dt;
        }
        catch (SqlException e)
        {
            return dt;
        }

You must need to create DataTable Object which is

DataTable dt = new DataTable();

  • Related