Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I have a windows form with two textbox,one combobox,one button and a datagridview .The datgridview is binded using stored procedure i.e when the textbox and combobox is filled and click button the datagridview must be populated.I need to populate datagridview only if there is a data.If the data is empty the datagidview should display "No records found".

What I have tried:

private void button2_Click(object sender, EventArgs e)
       {

           if (txt_VoucherNo.Text.Trim() != "")
           {
               Voucher = txt_VoucherNo.Text.Trim();
           }
           if (ddl_prt.SelectedValue.ToString().Trim() != "")
           {
               prt = ddl_prtSelectedValue.ToString().Trim();
           }

           if (batch.Text.Trim() != "")
           {
               batch = txt_batchno.Text.Trim();
           }


           //GET Data From Database
           var connectionstring=ConfigurationManager.ConnectionStrings["PROCConnectionString"].ConnectionString;
           SqlConnection cn = new SqlConnection(connectionstring);


           SqlCommand cmd = new SqlCommand();
           cmd.CommandType = CommandType.StoredProcedure;
           cmd.CommandText="SP44";

           cmd.Parameters.AddWithValue("Voucher", Voucher);
           cmd.Parameters.AddWithValue("prt", prt);
           cmd.Parameters.AddWithValue("batch", batch);
           cmd.CommandTimeout = 999999;
           cmd.Connection=cn;

           try
           {
               cn.Open();
               DataTable dt = new DataTable();
               //dt = cmd.ExecuteReader();
               SqlDataReader dr = cmd.ExecuteReader();
               dt.Load(dr);
               dataGridView1.DataSource = dt;



           }
           catch (Exception ex)
           {

           }
           finally
           {
               cmd.Connection.Close();
               cn.Close();
           }


       }


//This is my code when the button is clicked.Here the datgridview (only headers) are loaded if there is no data.How can I load the datagridview only if there is data.Any help will be really appreciated.
Posted
Updated 10-Oct-17 18:54pm

1 solution

try

DataTable dt = new DataTable();
         SqlDataAdapter da = new SqlDataAdapter(cmd);
         da.Fill(dt);
         if (dt.Rows.Count == 0) {
             DataTable dtNoRows = new DataTable();
             dtNoRows.Columns.Add("Info");
             dtNoRows.Rows.Add("No records found");
             dataGridView1.DataSource = dtNoRows;
         }
         else
             dataGridView1.DataSource = dt;
 
Share this answer
 
v2

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