DataList not displaying data - c#

So I have a DataSource and also a DataList:
<asp:SqlDataSource ID="SearchDataSource" runat="server"
ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\4WheelsDB.mdb;Persist Security Info=True"
ProviderName="System.Data.OleDb">
</asp:SqlDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SearchDataSource"></asp:DataList>
When a user clicks on a button it performs this code which amends the query according to what the user has chosen:
query = "SELECT * FROM Cars WHERE "
if(make != 1)
{
query = query + "make_id = #make";
SearchDataSource.SelectParameters.Add("make", make.ToString());
}
SearchDataSource.SelectCommand = query;
btn_search.Text = DataList1.Items.Count.ToString();
However when the datalist should show some rows the btn_search.Text displays 0 and rows are not shown in the datalist, does anyone know what I am doing wrong?

You should add where clause in your query.
C#
query = "SELECT * FROM Cars"
if(make != 1)
{
query = query + " where make_id = #make"; // add here
SearchDataSource.SelectParameters.Add("make", make.ToString());
}
SearchDataSource.SelectCommand = query;
btn_search.Text = DataList1.Items.Count.ToString();
ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SearchDataSource">
<ItemTemplate>
<asp:Label ID="lblmake_id" runat="server" Text='<%# Eval("make_id")%>' />
</ItemTemplate>
</asp:DataList>

Related

How can i filter values from column with checkboxes

Now what I need is, when I click on the checkbox dtGone, list need to filter for me all records with 74 value, or when I click another one need to show me all records with value 5.
public partial class WebForm1 : System.Web.UI.Page
{
protected void button1_Click1(object sender, EventArgs e)
{
string filterstatus = "";
if (dtGone.Checked)
{
if (dtStay.Checked)
{
filterstatus = "'74' ,";
}
else
{
filterstatus = "'74'";
}
}
if (dtStay.Checked)
{
if (dtGone.Checked)
{
filterstatus = "'5' ,";
}
else
{
filterstatus = "'5'";
}
}
using (SqlConnection db = new
SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
if (db.State == ConnectionState.Closed)
db.Open();
string query = "select something, id, idstatus, desc " +
" from table" +
$" where idstatus in (" + filterstatus + ")";
}
}
}
When I click the button to filter for me records they show me the following error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Here is the my aspx:
<form class="form-horizontal" id="form1" runat="server">
<div class="form-group">
<asp:Button ID="button1" runat="server" Text="Button" OnClick="button1_Click1" />
<asp:CheckBox ID="dtGone" runat="server" />
<asp:CheckBox ID="dtStay" runat="server" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns
<asp:BoundField DataField="something" HeaderText="barcode" SortExpression="barcode" />
<asp:BoundField DataField="id" HeaderText="idstatus" SortExpression="idstatus" />
<asp:BoundField DataField="idstatus" HeaderText="description" SortExpression="description" />
<asp:BoundField DataField="desc" HeaderText="idtype" SortExpression="idtype" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:_cl1_nlbConnectionString %>" SelectCommand="SELECT [something], [id], [idtstatus], [desc] FROM [table]"></asp:SqlDataSource>
</div>
</form>
Let's extract method:
private static IEnumerable<int> InValues() {
yield return -1; // dummy value; we don't want to have syntax error for "idstatus in ()"
if (dtGone.Checked)
yield return 74;
if (dtStay.Checked)
yield return 5;
}
Then you can easily build the query:
string query =
$#"select something,
id,
idstatus,
desc -- desc may appear to be a reserved word which you should escape
from table -- table may appear to be a reserved word which you should escape
where idstatus in ({string.Join(", ", InValues())})";
If one and only one of dtGone and dtStay can be checked, you can simplify the code:
string query =
$#"select something,
id,
idstatus,
desc -- desc may appear to be a reserved word which you should escape
from table -- table may appear to be a reserved word which you should escape
where idstatus = {(dtGone.Checked ? 74 : 5)}";

Marquee from database in asp.net

First, I used marquee with repeater and it is working fine, but it shows all data at the same time.
My code look like this :
<marquee id="ml" style="text-align: center" width="400px" height="170"
scrolldelay="5" scrollamount="5">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<br />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("notification") %>'></asp:Label><br />
</ItemTemplate>
</asp:Repeater>
</marquee>
Here is my code behind page below:
private void getnotification()
{
DataTable notifydt = new DataTable();
DateTime currentdt = DateTime.Now;
string date1 = currentdt.ToString("yyyy-MM-dd");
string qry = "";
qry = "select notification from adminnotification where visibility=1 and FromDate >='" + date1 + "'";
SqlDataAdapter sda = new SqlDataAdapter(qry, con);
StringBuilder sb = new StringBuilder();
con.Open();
sda.Fill(notifydt);
int count = notifydt.Rows.Count;
DataView dv = new DataView(notifydt);
if (count > 0)
{
foreach (DataRow DR in notifydt.Rows)
{
dv.RowFilter = "notification='" + DR["Notification"].ToString()+ "'";
}
Repeater1.DataSource = dv;
Repeater1.DataBind();
}
}
I want to show data one by one, how can I do that ?
Thank you in advance,
There are few things you can check
The Repeater control has no horizontal or vertical "direction". You either need to control it via css:
<ItemTemplate>
<div style="float:left">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("notification") %>' />
</div>
</ItemTemplate>
or use other controls like DataList, where you could set direction
<asp:DataList RepeatDirection="Horizontal" ... >
The following filter makes no sense and needs to be deleted
foreach (DataRow DR in notifydt.Rows)
{
dv.RowFilter = "notification='" + DR["Notification"].ToString()+ "'";
}
The filter by date could be set directly in sql. For example, if you use SQL Server then you could use the getdate() function
where visibility=1 and FromDate >= getdate()
To get only date you could use Convert(date, getdate()), see documentation for your database for more details.

Perform a SQL query search based on one or both user inputs and populate a grid view with the results

I am working on a small search form that has two text fields: One that allows users to search for a job list (which is basically a wish list--don't know why they want to call it a "job list" but whatever) by entering in part of or a full email address or someone's first and/or last name (This textbox is called SearchName). This field is required and if it is blank when the user hits "Search," an error message appears telling them so. The second textbox is optional, and it allows users to enter in a city or a state to help narrow their search down even more (this textbox is called SearchLocation).
I have a function (called getJobLists()) that is used by the search button to get results.
As it is right now, the part of the function that returns results based on what is entered into the SearchName field works perfectly. However, I cannot get any results for SearchLocation. When I enter a valid email or name into SearchName, then enter a valid city or state into SearchLocation, I get no results. However, if I enter in anything invalid (i.e. a city that is not associated with the entered email or name) the "no results found" message does appear.
I have tested both SQL queries in my search function in SQL Server Management Studio and they do work perfectly.
I have a try-catch inside the search function, but no error is being shown, not even in the console.
This is the code behind:
protected void Page_Load(object sender, System.EventArgs e)
{
// CHECK IF THE WISHLIST SEARCH ENABLED
StoreSettingsManager settings = AbleContext.Current.Store.Settings;
if (!settings.WishlistSearchEnabled)
{
Response.Redirect(AbleCommerce.Code.NavigationHelper.GetHomeUrl());
return;
}
}
protected void getJobLists()
{
try
{
if (SearchName.Text != "")
{//if SearchName.Text is not blank
if (SearchLocation.Text != "")
{//check to see if SearchLocation.Text is not blank either
string sqlSelect = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%') AND ((City + Province) LIKE '%'+#Location+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.Parameters.AddWithValue("#Location", String.Format("%{0}%", SearchLocation.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl = ds.Tables.Add("jobsListsTbl");
jobsListsTbl.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl.NewRow();
dr["User"] = reader["Name"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl";
WishlistGrid.DataBind();
}
}//end of if(SearchLocation.Text !='')
else
{//if SearchLocation.Text is blank, then go with this code instead
string sqlSelect2 = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect2, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl2 = ds.Tables.Add("jobsListsTbl2");
jobsListsTbl2.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl2.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl2.NewRow();
dr["User"] = reader["UserName"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl2.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl2";
WishlistGrid.DataBind();
}
}//end if SearchLocation.Text is empty
}//end of if SearchName.Text !==''
}
catch (Exception x)
{
errors5.Text += "ERROR: " + x.Message.ToString() + "<br />";
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
WishlistGrid.Visible = true;
getJobLists();
}
And this is the designer code for the search form (Note: the NavigateUrl is not set for the hyperlink yet. I will set it once everything is displaying properly for the search results):
<div id="findWishlistPage" class="mainContentWrapper">
<div class="section">
<div class="introDiv">
<div class="pageHeader">
<h1>Find a Job List</h1>
</div>
<div class="content">
<asp:label id="errors" runat="server" text=""></asp:label>
<asp:label id="errors2" runat="server" text=""></asp:label>
<asp:label id="errors3" runat="server" text=""></asp:label>
<asp:label id="errors4" runat="server" text=""></asp:label>
<asp:label id="errors5" runat="server" text=""></asp:label>
<asp:UpdatePanel ID="Searchajax" runat="server">
<ContentTemplate>
<asp:Panel ID="SearchPanel" runat="server" EnableViewState="false" DefaultButton="SearchButton">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableViewState="false" />
<table class="inputForm">
<tr>
<th class="rowHeader">
<asp:Label ID="SearchNameLabel" runat="server" Text="Name or E-mail:" AssociatedControlID="SearchName" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:Textbox id="SearchName" runat="server" onfocus="this.select()" Width="200px" EnableViewState="false"></asp:Textbox>
<asp:RequiredFieldValidator ID="SearchNameValdiator" runat="server" ControlToValidate="SearchName"
Text="*" ErrorMessage="Name or email address is required." EnableViewState="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="rowHeader">
<asp:Label ID="SearchLocationLabel" runat="server" Text="City or State (optional):" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:TextBox id="SearchLocation" runat="server" onfocus="this.select()" Width="140px" EnableViewState="false"></asp:TextBox>
<asp:LinkButton ID="SearchButton" runat="server" CssClass="button linkButton" Text="Search" OnClick="SearchButton_Click" EnableViewState="false" />
</td>
</tr>
</table><br />
<asp:GridView ID="WishlistGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" ShowHeader="true"
SkinID="PagedList" Visible="false" EnableViewState="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderStyle CssClass="wishlistName" />
<ItemStyle CssClass="wishlistName" />
<ItemTemplate>
<asp:HyperLink ID="WishlistLink" runat="server" >
<%#Eval("User")%>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<HeaderStyle CssClass="wishlistLocation" />
<ItemStyle CssClass="wishlistLocation" />
<ItemTemplate>
<asp:Label ID="Location" runat="server" Text='<%#Eval("PrimaryAddress")%>'></asp:Label>
<%--'<%#GetLocation(Eval("User.PrimaryAddress"))%>'--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Localize ID="EmptySearchResult" runat="server" Text="There were no job lists matching your search criteria."></asp:Localize>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
Can anyone please tell me what I'm missing or doing wrong?
Okay, I finally solved the issue. Apparently, it was a variable naming issue I kept overlooking. But now it all works okay! :)

Bind a HiddenField within a gridview

I want to bind a Hidden Field because I want to pass a value from code behind to the asp:Parameter Name="HOME_TEAM_COACH_ID" Type="Int32".
My asp:
<asp:FormView ID="FormView1" runat="server" OnItemUpdated="FormView1_ItemUpdating" >
<EditItemTemplate>
HOME_TEAM:
<asp:DropDownList ID="DropDownListHometeam" runat="server"
DataSourceID="SqlDataGetTeams"
DataTextField="NAME" DataValueField="ID" SelectedValue='<%# Bind("HOME_TEAM_ID") %>'>
</asp:DropDownList>
<asp:HiddenField runat="server" ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>' />
</EditItemTemplate>
And c# behind is:
protected void FormView1_ItemUpdating(object sender, FormViewUpdatedEventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
DropDownList HomeTeamId = FormView1.FindControl("DropDownListHometeam") as DropDownList;
string team = string.Format("{0}", HomeTeamId.Text);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BasketballConnectionString1"].ToString());
conn.Open();
string queryHome = "SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")";
SqlCommand cmd = new SqlCommand(queryHome, conn);
var Home_Coach_Id = cmd.ExecuteScalar().ToString();
HiddenField HomeCoachIdLabel = FormView1.FindControl("testLabel") as HiddenField;
HomeCoachIdLabel.Value = Convert.ToString(Home_Coach_Id);
conn.Close();
I want Help with the last four lines where I want to pass the Home_Coach_Id value to bind the asp:HiddenField ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>'.
When I click update, it doesn't change the value in database. (When I debug, in the last lines it gives me the correct HomeCoachIdLabel.Value.)
any suggestions?
You do not need the explicitly set the HiddenField's Value property, because it is done by the <%# Bind("HOME_TEAM_COACH_ID") %> in your markup.
I believe your problem is that you are not returning the HOME_TEAM_COACH_ID from your query to the database in your SELECT statement:
SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH
INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID
WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")
The problem is that it needs the method prerender and not the method onitemupdated.
asp:FormView ID="FormView1" runat="server" OnPreRender="FormView1_OnPreRender" >
and also in c#
protected void FormView1_OnPreRender(object sender, FormViewUpdatedEventArgs e)
{
It also works when I put it in page load{ }.
The next step is to make the insert event....

Cannot get textbox value from textbox in itemtemplate

The quantity (quantityWanted in DB) in textbox is loaded via Eval() method from Basket DB table. What I want to achieve is that when I change quantity manually and click update the quantity for that record will be updated and then grid will be reloaded. I seem unable to retrieve value of that textbox in code behind.
I am aware of FindControl() method which is used to get value from controls within itemtemplate but I don't know how to use it here.
The tried below but always get nullReferenceException
TextBox txt = (TextBox)GridView2.FindControl("txtQuantityWanted");
int _quantity = Convert.ToInt16(txt.Text);
Note: button is there but does nothing.
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantityWanted" Text='<%# Eval("quantityWanted") %>' ></asp:TextBox>
<asp:LinkButton ID="LinkButton11" runat="server" CommandName="update" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Update</asp:LinkButton>
<asp:Button ID="Button21" runat="server" Text="Button" CommandName="edit" />
</ItemTemplate>
<asp:TemplateField HeaderText="Total [£]">
<ItemTemplate>
<asp:Label id="lblItemTotal" runat="server" Text='<%# String.Format("{0:C}", Convert.ToInt32(Eval("quantityWanted"))* Convert.ToDouble(Eval("price"))) %>' ></asp:Label>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="remove" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
// .....
else if (e.CommandName == "update")
{
string params = Convert.ToString(e.CommandArgument);
string[] arg = new string[2];
arg = params.Split(';');
name = Convert.ToString(arg[0]);
datetimeAdded = Convert.ToString(arg[1]);
const string strConn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=L:\ASP.NET\Exercise1\Exercise1\Exercise1\App_Data\ASPNETDB.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
DataSet ds = new DataSet("Employees");
SqlConnection connection = new SqlConnection(strConn);
// Here I need value from textbox to replace 11
SqlCommand abc = new SqlCommand("UPDATE Basket SET quantityWanted = 11 WHERE coffeeName LIKE '%" + name + "%' AND datetimeAdded LIKE '" + datetimeAdded + "' ", connection);
connection.Open();
int ii = abc.ExecuteNonQuery();
connection.Close();
}
}
Use GridView.Rows collection to find control. You can pass the index of row in rows collection indexer.
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
You must pass the row index as well,Your code will look like this
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
I hope it will work for you.
Control ctrl = e.CommandSource as Control;
if (ctrl != null)
{
GridViewRow gvRow = ctrl.Parent.NamingContainer as GridViewRow;
TextBox txt= (TextBox)gvRow.FindControl("txtQuantityWanted");
}

Categories

Resources