Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have created a database in sql in which I have provided a unique id to every entry and I want to fetch the entire data in C# using that unique id. Help me asap.

Edit - OP code from comment
C#
private void button1_Click_1(object sender, EventArgs e)
{
	SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=sales;Data Source=MERITECH-PC");
	con.Open();

	SqlCommand cmd = new SqlCommand("Select * from new", con);
	cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
	  
	SqlDataReader dr = cmd.ExecuteReader();
	if (dr.HasRows)
	{
		dr.Read();
		txt1.Text= dr[0].ToString();
		txt2.Text = dr[1].ToString();
		txt3.Text = dr[2].ToString();
		txt4.Text = dr[3].ToString();
		txt5.Text = dr[4].ToString();
	}
	con.Close();
}
Posted
Updated 19-Feb-15 22:37pm
v4
Comments
CHill60 19-Feb-15 7:20am    
What have you tried and where are you stuck?
Member 11154071 20-Feb-15 0:02am    
private void button1_Click_1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=sales;Data Source=MERITECH-PC");
con.Open();

SqlCommand cmd = new SqlCommand("Select * from new", con);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;

SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txt1.Text= dr[0].ToString();
txt2.Text = dr[1].ToString();
txt3.Text = dr[2].ToString();
txt4.Text = dr[3].ToString();
txt5.Text = dr[4].ToString();
}
con.Close();
CHill60 20-Feb-15 4:23am    
That's not XAML.
All that is missing from your query is the WHERE clause - where do you store the id you want to search on ?

1 solution

Here is your code (assuming your primary key is named id):
C#
private void button1_Click_1(object sender, EventArgs e)
{
	SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=sales;Data Source=MERITECH-PC");
	con.Open();
 
	//notice the addition below
    SqlCommand cmd = new SqlCommand("Select * from new where id=@id", con);
	cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
	  
	SqlDataReader dr = cmd.ExecuteReader();
	if (dr.HasRows)
	{
		dr.Read();
		txt1.Text= dr[0].ToString();
		txt2.Text = dr[1].ToString();
		txt3.Text = dr[2].ToString();
		txt4.Text = dr[3].ToString();
		txt5.Text = dr[4].ToString();
	}
	con.Close();
}
 
Share this answer
 

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