0

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();
        }
    }
4

1 回答 1

0

我觉得你在这之后......

    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();
            }
        }
    }
于 2012-07-15T06:55:45.383 回答