I am trying to populate a label using a T-Sql query to a SQL Server table upon a click event. I have the click event and linking to the SQL Server table working just fine. The process (below) returns "System.Windows.Forms.BindingSource" rather than any value from the table. My code is as follows.

string strCon = "Data Source=ITxxx;Initial Catalog=FDM;Integrated Security=True";
            // Mailed date
            string strSQLi = "select " +
                "Mailed_Dt " +
                "from [FDM].dbo.XREF_ProductTbl" +
                " where Product = " + " '" + cboxMailRespSelProgram.Text.ToString() + "'";
            SqlDataAdapter dataAdapterI = new SqlDataAdapter(strSQLi, strCon);
            SqlCommandBuilder commandBuilderI = new SqlCommandBuilder(dataAdapterI);
            DataTable tblProductI = new DataTable();
            BindingSource productIBindSource = new BindingSource();
            productIBindSource.DataSource = tblProductI;
            dataAdapterI.Fill(tblProductI);
            lblProductI.Text = "Mailed Date:  " + productIBindSource;

Your help will be greatly appreciated!

Recommended Answers

All 3 Replies

>Returning a single value from SQL Server query to a C# label,
Use ExecuteScalar method of SqlCommand class.

...
 object val=cmd.ExecuteScalar();
 ...

Using data adapters, command builders, etc is a little bit of overkill for the task at hand. As adatapost suggested you will want to use .ExecuteScalar() . Also keep in mind if the query may ever grow you will want to use a DataTable .

const string connStr = "Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;";
      const string query = "Select Password From UserTable (NOLOCK) Where UserName = @UserName";
      DataTable result = new DataTable();
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = Username;
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
            result.Load(dr);
            string textBoxStuff = Convert.ToString(result.Rows[0]["Column"]);
          }
        }
      }

Both responses were very helpful. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.