GridView is not visible on page - c#

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)

Related

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

Textboxes dont update when dropdownlist value is changed ASP.NET

I have four text boxes whose value I need to change based on the selection in a dropdown list. but when I change the value, the textboxes don't update
My codes:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Employees" runat="server"
ConnectionString="<%$ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT [FullName] FROM [Employees] ORDER BY [FirstName]">
</asp:SqlDataSource>
And class file:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string cn = "Data Source=.;Initial Catalog=DBRE ;Integrated Security=True";
SqlConnection scon = new SqlConnection(cn);
SqlCommand scmd = new SqlCommand("Select * from Employees where FullName = '" + DropDownList1.SelectedItem.Value + "'", scon);
SqlDataReader sdr;
try
{
scon.Open();
sdr = scmd.ExecuteReader();
txtName.Text = sdr["FirstName"].ToString();
txtSurname.Text = sdr["LastName"].ToString();
txtDepartment.Text=sdr["Dept"].ToString();
txtCostCentre.Text=sdr["CostCentre"].ToString();
}
catch (Exception ex)
{
}
finally
{
scon.Close();
}
What am i doing wrong here?
May be i think check the exception, Use Reader like or use ExecuteScalar
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
Check this
dynamically filled DropDownList does not retain value on postback ASP.net c#
Try EnableViewState="true"
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" EnableViewState="true" DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Set your dropdownlist with AutoPostBack="true" with the on selected index changed like this:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPNo_selectedChanged" ></asp:DropDownList>
And in your code behind load data into your dropdownlist with the following code:
String conn = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(conn);
SqlDataAdapter da = new SqlDataAdapter("select Code from table1", con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
con.Close();
ddl.DataSource = ds.Tables[0];
ddl.DataValueField = "Code";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("-- select --"));
}
}
Now you can bind data on dropdownlist changed with the following code:
protected void ddl_selectedChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
String strQuery = "select description from table1 where Code = #Code";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#Code", ddl.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtbdescription.Text = dr["description"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
where txtbdescription is the id of your textbox.
Hope this will help.
Remove AutoPostBack="True"
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
And add if (!ispostback) condition
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!isPostback)
{
string cn = "Data Source=.;Initial Catalog=DBRE ;Integrated Security=True";
SqlConnection scon = new SqlConnection(cn);
SqlCommand scmd = new SqlCommand("Select * from Employees where FullName = '" + DropDownList1.SelectedItem.Value + "'", scon);
SqlDataReader sdr;
try
{
scon.Open();
sdr = scmd.ExecuteReader();
txtName.Text = sdr["FirstName"].ToString();
txtSurname.Text = sdr["LastName"].ToString();
txtDepartment.Text=sdr["Dept"].ToString();
txtCostCentre.Text=sdr["CostCentre"].ToString();
}
catch (Exception ex)
{
}
finally
{
scon.Close();
}
}
}

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

No output from search button

I have a search button on my web page and it should return the subject name from the DB which are similar to entered search word, but I didnt get any out put when I use the following code... please help me to do it...
this is my C# code
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=localhost; database=e-learningsystem; uid=root; password=123;port=3307;");
connection.Open();
string srh = editbox_search.Type;
try
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name= LIKE %'" + srh + "'%", connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch
{
}
asp.net code:
<input name="editbox_search" class="editbox_search" id="editbox_search"
maxlength="80" type="text"
style="background-color: #99CCFF; margin-top: 0px; height: 15px;" runat="server"
enableviewstate="True" title="Search Courses:" clientidmode="Inherit"
dir="ltr" visible="True"/>
<asp:Button ID="Button1"
runat="server" Height="26px" Text="Go" Width="32px" />
<asp:GridView ID="GridView1" runat="server" ShowFooter="True"
Caption="<h3 style='background-color:teal;color:white;'>Search Results...</h3>"
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
</asp:GridView>
There is Mistake in Your Query, Correct it as below.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%" + srh + "%'", connection);
First, use a parameterized command to avoid SQL injections. Second, I think the value you are looking for is in the Text property of the input, not the Type property. Lastly, the single quotes go outside the matching characters, i.e., '%searchvalue%'.
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%#input%'", connection);
cmd.Parameters.Add("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this one:
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%'+#input+'%'", connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
MySqlDataReader dr = cmd.ExecuteReader();
da.Fill(dr);
GridView1.DataSource = dr;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this query
SELECT * FROM subject WHERE Name LIKE %'" + srh + "'%

Categories

Resources