Search code examples
c#sql-serverdatabaseparameterized-queryselect-query

How to execute parameterized select query on .mdf database and display a column value?


I have a SQL Server database file MsUser.mdf with a table MsAccount that has 5 columns:

userID   accountID   accountName   accountBalance   imageLocation

I need to find the accountBalance where accountID = combobox that being selected, and show it in labelBalance._text. AccountBalance is decimal, accountID is varchar(10).

I wrote the code at comboBox event selected index. Thanks for helping.

      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
      {
          string selected = comboBox2.SelectedItem.ToString();//typ0000001-cake
          int position = selected.IndexOf("-");
          string accountID = selected.Substring(0,position);//typ0000001
          SqlDataAdapter sdaUserID = new SqlDataAdapter("Select Count(accountBalance),accountBalance From MsAccount where accountID='" +accountID+"'", cn);
          DataTable dt1 = new DataTable();
          sdaUserID.Fill(dt1);
          lblBalance.text = dt1.Rows[0][1].ToString();

      }

Solution

  • I am glad you got your code working. In general, it would be better to create a parameterized query, but if security is not a major concern, then just a plain select SQL string will do the job (as in your case).

    Couple words regarding some performance optimization: I would recommend to use String.Concat(string1, string2) instead of string1+string2 approach, thus it would be better to modify the line from your code as shown below:

    SqlDataAdapter sdaUserID = new SqlDataAdapter(String.Concat ("Select Count(accountBalance),accountBalance From MsAccount where accountID='",accountID, "'"), cn);
    

    Best regards,