Last post Mar 29, 2018 12:53 AM by Ash93
Mar 28, 2018 06:18 AM|Ash93|LINK
Currently, I'm working on the Lucky Draw system. The process of the system is when a user clicks on the draw button it selects a random id from database where table attendance="Present". Can anyone help me on this? Thanks.
Here the code that i have tried :
public partial class _Default : System.Web.UI.Page
string constr = ConfigurationManager.ConnectionStrings["lucky"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
protected void Button1_Click(object sender, EventArgs e)
string query = "SELECT TOP 1[EMP_ID]FROM EMPLOYEES WHERE[Attendance] = 'Present'ORDER BY NEWID()";
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand(query))
using (SqlDataAdapter sda = new SqlDataAdapter())
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
if (dt.Rows.Count > 0)
Label1.Text = dt.Rows["EMP_ID"].ToString();
Label1.Text += "Cannot draw! ";
Mar 28, 2018 06:52 AM|PatriceSc|LINK
It's best to never post code without telling what happens. I see :
- seems you miss con.Open() to open the database connection
- your SQL statement could perhaps fail because of missing spaces
But iyour connection string could be wrong as well etc... Never try to debug code by reading it. Always start from what happens (error message or unexpected behavior).
Mar 28, 2018 06:57 AM|Ash93|LINK
Hi Patrice, when i run the project, the label just shows 'NaN' . It cannot select a data from database.
Mar 28, 2018 08:37 AM|oned_gk|LINK
use flag column for lucky person, update luckyflag=1 when he is a lucky person
Then when when randomize, exclude lucky person by adding NOT luckyflag=1 in criteria
Another way, use luckytable, random and insert the result to luckytable,
INSERT INTO luckytable ([EMP_ID]) SELECT TOP 1[EMP_ID]FROM EMPLOYEES
WHERE[Attendance] = 'Present' AND
NOT [EMP_ID] IN (SELECT [EMP_ID] FROM luckytable) ORDER BY NEWID()
display luckytable to see all results
Mar 28, 2018 09:37 AM|Prince Srivastava|LINK
Mar 28, 2018 09:45 AM|Ash93|LINK
Mar 28, 2018 11:15 AM|PatriceSc|LINK
In VS use F9 on the Label1.Text
Then F5 to run your app and it should stop when this line is reached. You could also see which value is assigned to Label1.Text.
play here ?
Mar 29, 2018 12:53 AM|Ash93|LINK