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.
Related
I have what I think is a simple question, however it might be more complex..
I have spent a few days looking for the answer on google and various questions on this site but cannot seem to come right.
What I am trying to do is to bind to a Gridview on the User Control ascx page from the Default.aspx.cs on the Page Load event.
User Control markup is as follows:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="VulnerabilityExternalIP.ascx.cs" Inherits="VulnerabilityAssesment.Controls.VulnerabilityExternalIP" %>
<asp:Table runat="server" CellPadding="1" CellSpacing="2">
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityName" runat="server" Text="Vulnerability Name:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityNameText" runat="server" Text='<%# Eval("MainVulnerabilityName") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityCategory" runat="server" Text="Category:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityCategoryText" runat="server" Text='<%# Eval("Category") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityPopularity" runat="server" Text="Popularity:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityPopularityText" runat="server" Text='<%# Eval("Popularity") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityRisk" runat="server" Text="Risk:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="blVulnerabilityRiskText" runat="server" Text='<%# Eval("RiskFactor") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<br />
<asp:Label ID="lblHostsAffected" runat="server" Text="Hosts Affected:" CssClass="itemName"></asp:Label>
<br />
<asp:TextBox ID="txtHostsAffected" runat="server" TextMode="MultiLine" Width="700px" ReadOnly="true" BroderWidth="0px" Text='<%# Eval("HostNamePort") %>'></asp:TextBox>
<asp:GridView ID="gvHostsAffected" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True">
</asp:GridView>
I am referencing the User Control on the Default.aspx as follows:
<%# Register Src="~/Controls/VulnerabilityExternalIP.ascx" TagName="VulnerabilityExternalIP" TagPrefix="uc1" %>
Within the default.asxp I have the following defined:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:ListView ID="lvVulnerabilityExternalIP" runat="server">
<ItemTemplate>
<uc1:VulnerabilityExternalIP Template="<%# Container.DataItem %>" runat="server" ID="vulnerabilityExtIP" name="vulnext" />
</ItemTemplate>
</asp:ListView>
</asp:Content>
The code behind on Default.aspx.cs is as follows:
namespace VulnerabilityAssesment
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string HostNamePort = "";
string VulnerabilityDesc = "";
string VulnerabilitySummary = "";
string VulnerabilitySolution = "";
string VulnerabilityCVE = "";
string VulnerbilityLink = "";
// Use connection string from Web.Config
string connection = ConfigurationManager.ConnectionStrings["csVulnerabilityAssesment"].ConnectionString;
//Create new SQL Connection
SqlConnection conn = new SqlConnection(connection);
//Create Stored Procedure Command and Declare Parameters
SqlCommand vulnerabilityHeader = new SqlCommand("[dbo].[_spGet_VulnerabilityHeader]", conn);
vulnerabilityHeader.CommandType = CommandType.StoredProcedure;
vulnerabilityHeader.Parameters.Add("#VulnerabilityReport", SqlDbType.VarChar).Value = "External IP Ranges";
//Create Data Adapter and Data Set
SqlDataAdapter sdaVulnerabilityHeader = new SqlDataAdapter(vulnerabilityHeader);
DataSet dsVulnerabilityHeader = new DataSet();
//Open Connection
conn.Open();
//Fill Data Adapter
sdaVulnerabilityHeader.Fill(dsVulnerabilityHeader);
//Fill in template
List<VulnerabilityTemplate> Template = new List<VulnerabilityTemplate>();
if (dsVulnerabilityHeader.Tables != null)
if (dsVulnerabilityHeader.Tables[0].Rows.Count == 0)
{
}
else
if (dsVulnerabilityHeader.Tables.Count > 0)
{
foreach (DataRow dr in dsVulnerabilityHeader.Tables[0].Rows)
{
string GroupID = dr["GroupSequence"].ToString();
//Declare Stored Procedue for Vulnerability Details and set Parameters
SqlCommand vulnerabilityDetail = new SqlCommand("[dbo].[_spGet_VulnerabilityDetail]", conn);
vulnerabilityDetail.CommandType = CommandType.StoredProcedure;
vulnerabilityDetail.Parameters.Add("#VulnerabilityReport", SqlDbType.VarChar).Value = "External IP Ranges";
vulnerabilityDetail.Parameters.Add("#GroupSequence", SqlDbType.VarChar).Value = GroupID;
// Declare SQL Data Adapter for Vulnerability Detail
SqlDataAdapter sdaVulnerabilityDetail = new SqlDataAdapter(vulnerabilityDetail);
DataSet dsVulnerabilityDetail = new DataSet();
// Fill Data Adapter
sdaVulnerabilityDetail.Fill(dsVulnerabilityDetail);
// Declare Stored Procedure for Vulnerability Summary and Set Paramters
SqlCommand vulnerabilitySummary = new SqlCommand("[dbo].[_spGet_VulnerabilitySummary]", conn);
vulnerabilitySummary.CommandType = CommandType.StoredProcedure;
vulnerabilitySummary.Parameters.Add("#VulnerabilityReport", SqlDbType.VarChar).Value = "External IP Ranges";
vulnerabilitySummary.Parameters.Add("#GroupSequence", SqlDbType.VarChar).Value = GroupID;
// Declare SQL Data Adapter for Vulnerability Detail
SqlDataAdapter sdaVulnerabilitySummary = new SqlDataAdapter(vulnerabilitySummary);
DataSet dsVulnerabilitySummary = new DataSet();
// Fill Data Adapter
sdaVulnerabilityDetail.Fill(dsVulnerabilityDetail);
sdaVulnerabilitySummary.Fill(dsVulnerabilitySummary);
foreach (DataRow row in dsVulnerabilityDetail.Tables[0].Rows)
{
if (HostNamePort != "")
HostNamePort += Environment.NewLine;
HostNamePort += row["HostnamePort"].ToString();
}
foreach (DataRow vulnerabilitySummaryRow in dsVulnerabilitySummary.Tables[0].Rows)
{
VulnerabilityDesc += vulnerabilitySummaryRow["VulnerabilityDesc"].ToString();
VulnerabilitySummary += vulnerabilitySummaryRow["VulnerabilitySummary"].ToString();
VulnerabilitySolution += vulnerabilitySummaryRow["VulnerabilitySolution"].ToString();
}
//myGrid.DataSource = dsVulnerabilityDetail.Tables[0];
//GridView myGrid = (GridView)lvVulnerabilityExternalIP.Items.FindControl("gvHostsAffected");
// Always returns null :(
GridView myGrid = (GridView)lvVulnerabilityExternalIP.FindControl("gvHostsAffected");
Template.Add(new VulnerabilityTemplate
{
MainVulnerabilityName = dr["MainVulnerabilityName"].ToString(),
Category = dr["Category"].ToString(),
Popularity = dr["Popularity"].ToString(),
Riskfactor = dr["RiskFactor"].ToString(),
HostNamePort = HostNamePort
//VulnerabilityDesc = VulnerabilityDesc,
//VulnerabilitySolution = VulnerabilitySolution,
//VulnerabilitySummary = VulnerabilitySummary
}
);
myGrid.DataBind();
}
}
lvVulnerabilityExternalIP.DataSource = Template;
lvVulnerabilityExternalIP.DataBind();
conn.Close();
}
// Below Does not work
protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DataTable table = (DataTable)e.Item.DataItem;
GridView myGrid = (GridView)e.Item.FindControl("gvHostsAffected");
myGrid.DataSource = table;
myGrid.DataBind();
}
}
}
}
I cannot seem to find the gvHostsAffected grid view to bind it to the dsVulnerabilityDetail.Tables[0] value (which should be a single column called HostsAffected, this result could return 1 or more rows.
I have included two things that I have tried denoted by the comment //Below does not work.
The Template.Add method does work and it populates necessary information on the user control.
Is there any way I can find the Gridview control during the iteration and populate it with the results from the dsVulnerabilityDetail data set?
Thank you in advance.
Update 10 April 2017
Below is the Code Behind for the WebControl, I see I forgot to include it in the original Question.
namespace VulnerabilityAssesment.Controls
{
public partial class VulnerabilityExternalIP : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public GridView myGridView
{
get
{
return gvHostsAffected;
}
set
{
gvHostsAffected = value;
}
}
}
}
The markup for Web Control include the answer by VDWWD.
First, add a public GridView property to the User Control
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public GridView myGridView
{
get
{
return GridView1;
}
set
{
GridView1 = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Then you can access it like yo would a GridView on the same page. The only thing left to do is to use FindControl to find the User Control inside the ListView
protected void Button1_Click(object sender, EventArgs e)
{
WebUserControl1 control = lvVulnerabilityExternalIP.Items[2].FindControl("vulnerabilityExtIP") as WebUserControl1;
control.myGridView.DataSource = mySource;
control.myGridView.DataBind();
}
I want change the listview data with checkboxlist items. But when checked 2 or multiply items write this error:
The variable name '#TId' has already been declared.
or
Index was outside the bounds of the array.
Please help me. :(
HTML:
<asp:ListView ID="ltvProduct" runat="server">
<ItemTemplate>
<asp:HyperLink runat="server" ID="hypProduct" NavigateUrl='<%#"show.aspx?NId="+Eval("MId") %>'>
<div class="col-lg-4 Border Text PContainer ">
<asp:Image runat="server" ImageUrl='<%#"/img/Gallery/"+Eval("PicUrl") %>' CssClass="padding-product" Width="240px" /><br />
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' CssClass="EnName"></asp:Label><br />
</div>
</asp:HyperLink>
</ItemTemplate>
</asp:ListView>
CHECKBOX BIND CODE:
SqlConnection conT = new SqlConnection(ConfigurationManager.ConnectionStrings["CSTR"].ConnectionString);
SqlCommand cmT = new SqlCommand("Select * from Type", conT);
SqlDataAdapter adpT = new SqlDataAdapter(cmT);
DataTable dtT = new DataTable();
adpT.Fill(dtT);
chkType.DataSource = dtT;
chkType.DataTextField = "Name";
chkType.DataValueField = "TId";
chkType.DataBind();
SELECTEDINDEXCHANGE:
string strconnectionP = ConfigurationManager.ConnectionStrings["CSTR"].ConnectionString;
SqlConnection objconnectionP = new SqlConnection(strconnectionP);
string strsqlP = "select * from Model where TId=#TId";
SqlCommand objcommandP = new SqlCommand(strsqlP, objconnectionP);
for (int i = 0; i < chkType.Items.Count; i++)
{
if (chkType.Items[i].Selected)
{
objcommandP.Parameters.AddWithValue("#TId", chkType.SelectedValue[i]);
objconnectionP.Open();
ltvProduct.DataSource = objcommandP.ExecuteReader();
ltvProduct.DataBind();
}
objconnectionP.Close();
}
}
In your SELECTEDINDEXCHANGE event you are executing your SqlCommand inside a loop for multiple times. If you want to use a SqlCommand multiple times you should clear your parameter everytime after executing SqlCommand. Use this line of code
objcommandP.Parameters.Clear();
Ater these lines
ltvProduct.DataSource = objcommandP.ExecuteReader();
ltvProduct.DataBind();
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>
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! :)
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");
}