Prevent duplicates when using LinkButton OnClick - c#

How can I make it so when two people click on the LinkButton at the same time it allows one then prevents the other? I have this form where people are claiming records for themselves but the problem is people click the LinkButton nearly at the same time and then it proceeds to the next page for both of them and they both think the record is theirs.
ASP.NET
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="waitingRep" OnItemDataBound="waitingRep_ItemDataBound"
OnPreRender="waitingRep_PreRender" OnItemCommand="waitingRep_ItemCommand"
runat="server">
<ItemTemplate>
<asp:LinkButton ID="claimBtn" OnClick="claim" CommandArgument='<%# Eval("ID") %>' runat="server">
Claim
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
protected void claim(object sender, EventArgs e)
{
var location = Request.Params["lid"];
string logon_user = Request.LogonUserIdentity.Name.Substring(7);
LinkButton claimButton = (LinkButton)(sender);
int currentID = Convert.ToInt32(claimButton.CommandArgument);
bool isTaken = false;
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT COUNT(*) as isTaken FROM ClaimList WHERE ID = '" + currentID + "' AND Status = 2", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToInt32(rdr["isTaken"]) > 0) isTaken = true;
}
rdr.Close();
}
if (!isTaken)
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"UPDATE ClaimList set Status=#f1, ClaimedBy=#f2, ClaimedDate=#f3 where ID=#f4", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.Int).Value = 2;
cmd.Parameters.Add("#f2", SqlDbType.Int).Value = logon_user;
cmd.Parameters.Add("#f3", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.Parameters.Add("#f4", SqlDbType.Int).Value = currentID;
cmd.ExecuteNonQuery();
}
Response.Redirect("View.aspx?id=" + currentID);
}
else
{
Response.Redirect("Location.aspx?lid=" + location + "&action=taken");
}
}

Remove the select and add an extra condition to your update to avoid updating if it is already taken, like this:
bool isTaken = false;
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"UPDATE ClaimList set Status=#f1, ClaimedBy=#f2, ClaimedDate=#f3 where ID=#f4 AND Status <> 2", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.Int).Value = 2;
cmd.Parameters.Add("#f2", SqlDbType.Int).Value = logon_user;
cmd.Parameters.Add("#f3", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.Parameters.Add("#f4", SqlDbType.Int).Value = currentID;
if (cmd.ExecuteNonQuery() == 0)
isTaken = true;
}
if (!isTaken)
Response.Redirect("View.aspx?id=" + currentID);
else
Response.Redirect("Location.aspx?lid=" + location + "&action=taken");

Related

Find the value in gridview using findcontrol and comapre it with data in database

protected void LinkButton_Click(Object sender, EventArgs e)
{
String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
DateTime time = DateTime.Now; // Use current time
string format = "yyyy-MM-dd HH:mm:ss";
string UserName4 = HttpContext.Current.User.Identity.Name;
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
Label lblStudentId = (Label)grdrow.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
String query = "insert into voting (CandidateStudentID,voterStudentID,DateTime)values ('" + lblStudentId.Text + "','" + Session["UserName"].ToString() + "','" + time.ToString(format) + "')";
foreach (GridViewRow row in GridView2.Rows)
{
Label lblVoter = row.FindControl("lblVoter") as Label;
string voterID = lblVoter.Text;
if (Session["UserName"].ToString().Equals(lblVoter.Text))
{
Label1.Text = "You voted before";
}
}
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label2.Text = "Thank you for You Vote";
}
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" Font-Size="Medium">
<Columns>
<asp:TemplateField HeaderText="Student ID">
<ItemTemplate>
<asp:Label ID="lblVoter" runat="server" Width="150px" Text='<%#Eval("voterStudentID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void loadCandidate()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select studentID ,name from candidate ", con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
con.Open();
MySqlCommand cmd2 = new MySqlCommand("select voterStudentID from voting ", con);
MySqlDataReader dr2 = cmd2.ExecuteReader();
GridView2.DataSource = dr2;
GridView2.DataBind();
}
}
StudentID display in gridview2
I want to prevent duplicate voting in the database. Now I'm facing a problem which when the user login as first users in the StudentID table which is 1909404, when the 1909404 already exist in the database, It will display the error message. But when the user's login as the second user in the StudentID table which is 1909362, even though the user ID already exists, It will no show the error message. I would like to show the error message as long as the user ID existed in the database (which mean they voted before).
Change it like this....
foreach (GridViewRow row in GridView2.Rows) {
Label lblVoter = row.FindControl("lblVoter") as Label;
if (Session["UserName"].ToString().Equals(lblVoter.Text)) {
Label1.Text = "You voted before";
return;
}
}
// Since we looped through all the rows and did NOT find a match...
// Then they can vote
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label2.Text = "Thank you for You Vote";

How can I bind AutoCompleteExtender to dynamically created control?

The autofill works for the static text box, but not the dynamic one.
User needs to be able to add as many rows as necessary, and each text box should pull from the same table. There are too many records in the table to use a simple drop down... Any ideas?
This Works
<form id="TestForm" runat="server">
<asp:ScriptManager ID="thisNameDoesntMatter" runat="server"
EnablePageMethods="true" />
<asp:TextBox ID="noteValue" runat="server" OnTextChanged="noteValue_TextChanged" CausesValidation="true" Width="1000"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="searchNoteValues"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="noteValue"
ID="AutoCompleteExtenderNoteValues" runat="server" FirstRowSelected="false"/>
</form>
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> searchNoteValues(string prefixText, int count)
{
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, NoteValue FROM agl.GuidelineNoteValues where isActive = 1 and NoteValue like '%' + #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
con.Open();
List<string> NoteValues = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
NoteValues.Add(sdr["NoteValue"].ToString());
}
}
con.Close();
return NoteValues;
}
This Does Not
<form id="TestForm" runat="server">
<asp:ScriptManager ID="thisNameDoesntMatter" runat="server"
EnablePageMethods="true" />
<asp:PlaceHolder ID="TestPlaceHolder" runat="server" />
<asp:LinkButton ID="TestAddNoteButton" runat="server" Text="Add a note" OnClick="TestAddNoteButton_Click" CausesValidation="false" AutoPostBack="true"/>
</div>
</form>
Table notesTable = new Table();
protected void Page_PreRender(object sender, EventArgs e)
{
Session["table"] = notesTable;
}
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
notesTable.ID = "MyTable";
}
else
{
notesTable = (Table)Session["table"];
TestPlaceHolder.Controls.Add(notesTable);
}
}
protected void TestAddNoteButton_Click(object sender, EventArgs e)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, name FROM agl.guidelineNoteCategories";
con.Open();
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
dAdapter.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
System.Web.UI.WebControls.ListBox lb = new System.Web.UI.WebControls.ListBox();
System.Web.UI.WebControls.TextBox tb = new System.Web.UI.WebControls.TextBox();// { ID = sna.ToString()};
tb.Width = 1000;
tb.ID = "tb";
AjaxControlToolkit.AutoCompleteExtender ace = new AjaxControlToolkit.AutoCompleteExtender();
ace.ServiceMethod="searchNoteValues";
ace.MinimumPrefixLength=2;
ace.CompletionInterval=100;
ace.EnableCaching=false;
ace.CompletionSetCount=10;
ace.TargetControlID="tb";
ace.FirstRowSelected=false;
lb.BorderColor = System.Drawing.Color.Orange;
lb.DataSource = objDs.Tables[0];
lb.DataTextField = "name";
lb.DataValueField = "id";
lb.DataBind();
lb.Items.Insert(0, "--Select--");
tc1.Controls.Add(lb);
tc2.Controls.Add(tb);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
notesTable.Rows.Add(tr);
Session["table"] = notesTable;
ViewState["dynamictable"] = true;
}
con.Close();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> searchNoteValues(string prefixText, int count)
{
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, NoteValue FROM agl.GuidelineNoteValues where isActive = 1 and NoteValue like '%' + #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
con.Open();
List<string> NoteValues = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
NoteValues.Add(sdr["NoteValue"].ToString());
}
}
con.Close();
return NoteValues;
}
}
Got it. Wasn't adding the auto complete extender to the form.
TestForm.Controls.Add(ace);

How to bind selected value from database in dropdownlist in asp.net

I am trying to bind a selected item from the database in dropdownlist. I am not getting the users selected data in the dropdownlist instead it loads everything. What i need is to have a default selected value from the database along with other items. Please help me to overcome this problem. Thanking you in advance.
Stored procedure:
CREATE PROCEDURE [dbo].[get_student_details]
#StudentId int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT
dbo.Student.InstituteId,
dbo.Student.Institute,
dbo.Student.Name,
dbo.Student.Gender,
dbo.Student.Age
FROM
dbo.Student
WHERE
dbo.Student.StudentId = #StudentId
END
My .aspx markup:
<asp:DropDownList ID="ddlInstitute" runat="server"></asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:Button ID="btnPersonalDetails" runat="server" Text="Search" OnClick="GetStudentDetails"/>
My code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillInstitute();
}
}
public void FillInstitute()
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_Institute";
cmd.Connection = con;
try
{
con.Open();
ddlInstitute.DataSource = cmd.ExecuteReader();
ddlInstitute.DataTextField = "Institute";
ddlInstitute.DataValueField = "InstituteId";
ddlInstitute.DataBind();
ddlInstitute.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
public void GetStudentDetails()
{
studentid= 123;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_student_details";
cmd.Parameters.Add("#StudentId", SqlDbType.Int).Value = studentid;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
txtName.Text = dr["Name"].ToString();
txtGender.Text = dr["Gender"].ToString();
txtAge.Text = dr["Age"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
You have to use SelectedValue property of DropDownList.DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.
Replace these lines:
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
with:
ddlInstitute.SelectedValue= dr["InstituteId"].ToString();
or you can also do:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
You can also refer this article
Assuming you know which ID you want to have selected, try something like this:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
Try it as a function:
void FN_loadBranch()
{
classname cls = new classname ();
DataTable dt = new DataTable();
dt = cls.FUNCTIONNAMEINCLASS(int id);
dropdown.DataSource = dt;
dropdown.DataValueField = "valuefield";
dropdown.DataTextField = "textfield";
dropdown.DataBind();
ddlBranch.Items.Insert(0, new ListItem("--Select--", "0"));
}
In function:
public DataTable FUNCTIONNAMEINCLASS( int id)
{
try
{
using (SqlConnection cn = new SqlConnection(CLASS.ConnectionString))
{
SqlCommand cmd = new SqlCommand("[storedprocedure]", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar, 50).Value = id;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
Use stored procedure in the function

FileUpload with its updation status

I want to make a functionality where a User will upload the file and its name and description will be shown in the gridview.
Now here what I want is, if the same file has some changes, it needs to be uploaded again and the since its uploaded for the second time. I will be having one more column as FileRevision which will show the no of times files has been updated.
See the image for your reference:-
Do let me know from where to start.
I got it done by myself, like below:-
FileUpload Control in ASPX page
<asp:FileUpload ID="fupreportfile" runat="server" CssClass="form-control" ValidationGroup="AddNew" />
Now, on button click it will check whether the file Exist or not. Checking thorugh CS code:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
using (SqlCommand cmd = conn.CreateCommand())
{
if (fupreportfile.HasFiles)
{
int count = CheckFileExists(fupreportfile.PostedFile.FileName);
fupreportfile.SaveAs(Server.MapPath("~/ReportFolder/" + fupreportfile.PostedFile.FileName));
if (count > 0)
{
cmd.CommandText = " Update tbl_reports SET revision=#revision Where Id=#Id";
cmd.Parameters.AddWithValue("#Id", GetIdByFileName(fupreportfile.PostedFile.FileName));
cmd.Parameters.Add("#revision", SqlDbType.VarChar).Value = (count + 1).ToString();
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Reports updated sucessfully');window.location ='csrreports.aspx';", true);
}
else
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_reports (NgoId,report_type_id,report_title,report_file,report_desc,revision) values(#NgoId, #report_type_id, #report_title,#report_file,#report_desc,#revision)", conn);
cmd1.Parameters.Add("#NgoId", SqlDbType.Int).Value = ddlNgoName.SelectedValue;
cmd1.Parameters.Add("#report_type_id", SqlDbType.Int).Value = ddlReportType.SelectedValue;
cmd1.Parameters.Add("#report_title", SqlDbType.NVarChar).Value = txtreporttitle.Text;
cmd1.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fupreportfile.PostedFile.FileName;
cmd1.Parameters.Add("#report_desc", SqlDbType.NVarChar).Value = txtreportdescription.Text;
cmd1.Parameters.Add("#revision", SqlDbType.VarChar).Value = (count + 1).ToString();
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Reports added sucessfully');window.location ='csrreports.aspx';", true);
}
}
}
}
Code for checking file :-
public int CheckFileExists(string fileName)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tbl_reports WHERE report_file=#report_file", con);
cmd.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fileName;
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
}
Also, I need to check the ID for which Row it is updating. So the code for that is
public int GetIdByFileName(string fileName)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT Id FROM tbl_reports WHERE report_file=#report_file", con);
cmd.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fileName;
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
}
I checked this and it worked for me :)

data is not shown in label using datareader

I am new in the ASP.NET field and I made a function like:
public void lbtitle()
{
IDataReader dr = d.FetchDataReader("SELECT top(5) ItineraryMaster.ItinerariesId, ItineraryMaster.Title FROM ItineraryMaster WHERE ItineraryMaster.Title = '" + lbltitle.Text + "'");
if (dr.Read())
{
lbltitle.Text = dr["Title"].ToString();
}
}
and behind code is:
<asp:Label ID="Lbl_id" runat="server" Text='<%#Eval("ItinerariesId") %>' Visible="false"></asp:Label>
<asp:Label ID="lbltitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
the control is not gone on the dr.read() function.
I don't know why this is happening.
and data reader code is:
public SqlDataReader FetchDataReader(string sqlQuery)
{
SqlDataReader tempDataReader = (SqlDataReader) objSqlDatabase.ExecuteReader(CommandType.Text, #sqlQuery);
return tempDataReader;
}
why you are confusing yourself.
complete all tasks inside using statement. no need to define multiple functions to implement this. here i have modified code . try this
string connstring = ConfigurationManager.ConnectionStrings["myconnstring"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connstring))
{
cn.Open();
string title = lbltitle.Text.Trim();
string query = #"SELECT top(5) ItinerariesId, Title
FROM ItineraryMaster WHERE ItineraryMaster.Title = #title";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.Add(new SqlParameter("#title", title));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lbltitle.Text = lbltitle.Text.ToString() + "<br/>" + dr["Title"].ToString();
}
}

Categories

Resources