data is not shown in label using datareader - c#

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

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";

rating value is not appearing

how to get rating ajax id from a data list in code behind
asp.net.The value of the rating should come from database and display
.
web form
<asp:datalist id="viewjobdetails" clientidmode="Static" runat="server" datakeynames="Job_ID">
<itemtemplate>
<ajaxtoolkit:rating id="Ratinghk" runat="server" behaviorid="RatingBehavior1"
="" currentrating="0" maxrating="5" starcssclass="ratingStar" waitingstarcssclass="savedRatingStar" filledstarcssclass="filledRatingStar" emptystarcssclass="emptyRatingStar" style="float: left;">
<asp:label id="lblRatingStatus" runat="server">
</<ajaxtoolkit></itemtemplate>
</asp:datalist>
Code Behind
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT ISNULL(AVG(Reviews), 0) AverageRating, COUNT(Reviews) RatingCount FROM tblHKHOReviews where HK_ID=" + Request.QueryString["ID"]);
Ratinghk.CurrentRating = Convert.ToInt32(dt.Rows[0]["AverageRating"]);
lblRatingStatus.Text = string.Format("{0} Users have rated. Average Rating {1}", dt.Rows[0]["RatingCount"], dt.Rows[0]["AverageRating"]);
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(_conString))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}

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);

Prevent duplicates when using LinkButton OnClick

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");

GridView is not visible on page

I'm trying to fill a Gridview with data from a database view. I cant use linq because the view has 200+k rows i have to show. here is my code:
public partial class _Default : System.Web.UI.Page
{
private string mobileGateway = "MobileGateway";
private List<string> addressReport = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
GetReport(addressReport);
}
public void GetReport(List<string> adr)
{
string connecntionString = ConfigurationManager.ConnectionStrings[mobileGateway].ConnectionString;
using (SqlConnection connection = new SqlConnection(connecntionString))
{
try
{
connection.Open();
string sqlCmd = "SELECT * from dbo.BarcodeWithLocation";
using (SqlCommand command = new SqlCommand(sqlCmd, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
adr.Add("" + reader[0]);
adr.Add("" + reader[1]);
adr.Add("" + reader[2]);
adr.Add("" + reader[3]);
adr.Add("" + reader[4]);
adr.Add("" + reader[5]);
adr.Add("" + reader[6]);
adr.Add("" + reader[7]);
adr.Add("" + reader[8]);
adr.Add("" + reader[9]);
adr.Add("" + reader[10]);
}
Grid.DataSource = adr;
Grid.DataBind();
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR!!!!: " + ex.Message);
}
}
}
}
}
aspx code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AddressReporting._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:GridView ID="Grid" runat="server" AllowPaging="True"
AutoGenerateColumns="False">
</asp:GridView>
</asp:Content>
I get a blank page with no gridview at all. what am i doing wrong ?
enter code here
command.CommandType = System.Data.CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
Grid.DataSource = reader;
Grid.DataBind();
try this it will get all the details into reader and bind it to grid directly. No need to loop through all the rows unless you want to do something else there.
Try something like this:
string sqlCmd = "SELECT * from dbo.BarcodeWithLocation";
using (SqlCommand command = new SqlCommand(sqlCmd, connection))
{
DataTable dataTable = new DataTable();
command.CommandType = System.Data.CommandType.Text;
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(dataTable);
Grid.DataSource = dataTable;
Grid.DataBind();
}
Check whether you query is fetching data or not as you can't see empty GridView
Try declaring ref
public void GetReport(ref List<string> adr)
ref (C# Reference)

Categories

Resources