I am trying to make a web application which shows you some words and their definitions. But I couldn't figure out how to get the words from the database? My database's name is "WordsDB". I have 2 columns. the one is "Word" and the other one is "Definition".
(Also there is an ID column). I want it to get the words randomly from the database when the applicaitons starts. And also there will be a button called "Another word". And this buttton will get another word randomly. Should I do its event same as the main
event?
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=WordsDB;Integrated Security=True");
con.Open();
string ss = "select top 1 Word from testtable order by newid()";
SqlCommand cmd = new SqlCommand(ss, con);
SqlDataReader reader=cmd.ExecuteReader();
while (reader.Read())
{
Response.Write(reader.GetString(0));
}
con.Close();
}
Hope it can help.
Best Regards,
Amy Peng
Please mark the replies as answers if they help or unmark if not.
Feedback to us
Mac14
Member
46 Points
71 Posts
How to get data randomly?(c#)
Feb 21, 2013 05:53 PM|LINK
Hello everyone!
I am trying to make a web application which shows you some words and their definitions. But I couldn't figure out how to get the words from the database? My database's name is "WordsDB". I have 2 columns. the one is "Word" and the other one is "Definition". (Also there is an ID column). I want it to get the words randomly from the database when the applicaitons starts. And also there will be a button called "Another word". And this buttton will get another word randomly. Should I do its event same as the main event?
I am waiting for your answers,
Thank you for your help!
Nasser Malik
Star
11554 Points
1778 Posts
Re: How to get data randomly?(c#)
Feb 21, 2013 07:57 PM|LINK
You can get random word by tsql query
Skype: maleknasser1
Amy Peng - M...
Star
10151 Points
963 Posts
Microsoft
Re: How to get data randomly?(c#)
Feb 22, 2013 07:37 AM|LINK
Hi,
Please try to refer to the following code:
protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=WordsDB;Integrated Security=True"); con.Open(); string ss = "select top 1 Word from testtable order by newid()"; SqlCommand cmd = new SqlCommand(ss, con); SqlDataReader reader=cmd.ExecuteReader(); while (reader.Read()) { Response.Write(reader.GetString(0)); } con.Close(); }Hope it can help.
Best Regards,
Amy Peng
Feedback to us
Develop and promote your apps in Windows Store
ashkc
Participant
960 Points
200 Posts
Re: How to get data randomly?(c#)
Feb 22, 2013 10:46 AM|LINK
Mac14
Member
46 Points
71 Posts
Re: How to get data randomly?(c#)
Feb 23, 2013 04:21 PM|LINK
Thank you everyone for your answers!
Amy, thanks for the code. It works fine!
Have a great day!