简体   繁体   中英

Fetching data from SQL Server 2005 using c#

I would like to retrieve a particular column from a table when the values from two other columns are equal. My code is as follows. The four columns are id,destination,source,price .

I want to display the price when the destination and source are equal.

Could you please help me?

private void button1_Click(object sender, EventArgs e)
{

        SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter();

        DataTable dt = new DataTable();
        da.SelectCommand = new SqlCommand("select  price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
        da.Fill(dt);
        for(int i=0;i<dt.Rows.Count;i++)
        {
            textBox3.Text = dt.Rows[0][3].Count.ToString();
        }
    }

I thing you are after this ....

    private void button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
        {
            string query = "select  price from metro where source= @Source and destination = @Destination";

            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@Source", textBox1.Text);
                cmd.Parameters.AddWithValue("@Destination", textBox2.Text);

                con.Open();
                object o  = cmd.ExecuteScalar();
                if(o != null && o != DBNull.Value)
                {
                   string price = (string) o; //please cast the return type as required
                   textBox3.Text = price;
                }
                con.Close();
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM