How to return asp:repeater count - c#

I have searching implemented in my app, and it goes to a results page where the results populate a table through an asp:repeater. I'll include the code below.
C#
namespace WebApplication {
public partial class SearchResults : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Request.Params["searchterm"] != null) {
ResultLabel.Text = "Search results for: " + Request.Params["searchterm"];
string searchTerm = Request.Params["searchterm"];
int results = 0; //If I were to set it on back end
string constr = ConfigurationManager.ConnectionStrings["CurrencyDb"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr)) {
using (SqlCommand cmd = new SqlCommand("dbo.SearchProc", con)) {
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SearchTerm", searchTerm);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
ResultsTableRepeater.DataSource = ds;
ResultsTableRepeater.DataBind();
}
catch (SqlException sqlex) {
throw new Exception("SQL Exception loading data from database. " + sqlex.Message);
}
catch (Exception ex) {
throw new Exception("Error loading results data from database. " + ex.Message);
}
}
}
}
}
}
}
asp.net
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<br />
<br />
<br />
<br />
<asp:Label ID="ResultLabel" runat="server"></asp:Label>
<br />
<br />
<br />
<br />
<asp:Repeater ID="ResultsTableRepeater" runat="server">
<HeaderTemplate>
<table class="td-table-bordered">
<th>Currency Id</th>
<th>Component</th>
<th>Version</th>
<th>Vendor</th>
<th>Tech Owner</th>
<th>Tech Contact</th>
<th>Fiscal Consideration</th>
<th>Currency Status</th>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("CurrencyId") %></td>
<td><asp:HyperLink ID="UpdateLink" NavigateUrl='<%# Eval("CurrencyId", "http://10.155.54.101/Update?CurrencyId={0}") %>' runat="server" Target="_blank"><%# Eval("Model") %></asp:HyperLink></td>
<td><%# Eval("Version") %></td>
<td><%# Eval("Vendor") %></td>
<td><%# Eval("Tech Owner") %></td>
<td><%# Eval("Tech Contact") %></td>
<td><%# Eval("FiscalConsideration") %></td>
<td><%# Eval("Status") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<asp:Label ID="StatusLabel" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
</asp:Repeater>
<br />
</asp:Content>
What I would like to do is print a number how many results were returned in the footer. But I can't seem to find a way to do that throughout all of my searching, despite it seeming like it should be a simple task.
Is there a way, whether it be in the C# code behind or in the aspx directly to print how the amount of results at the end? It would be easy if there were a while(reader.read) loop to increment a counter, however that's not the case.
Thanks in advance so much for your help!

You can use the return value of sda.Fill(ds);:
As the documentation for Fill says:
Return Value: The number of rows successfully added to or refreshed in the DataSet.
Thus:
int rowsReturned = sda.Fill(ds);
Then you can assign the value in the footer.

Here is a similar issue here:
Determine the repeater row count in asp.net
Hope this helps you out! Should just be able to use their solution anywhere in your codebehind to get the Count, and then display it where ever you need it in your footer (assuming your repeater is already populated when you try to get the count).

Related

Multiple Images upload with different titles

My Requirement is. I will be uploading 3-4 images at a time through FileUpload. Each Image will have its own Title, Descriptions etc.
Now my issue is that, whenever uploading I have given a title column for the images. But when I upload 3-4 Images the title and description is going same for all the images.
Here Is my HTML for the Image Uploading via FileUpload.
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label1" runat="server">Image Title</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:textbox id="txtImagetitle" cssclass="form-control" runat="server" validationgroup="AddNew"></asp:textbox>
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator1" runat="server"
controltovalidate="txtImagetitle" errormessage="Please add the image title" validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label2" runat="server">Image description</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:textbox id="txtImagedesc" cssclass="form-control" runat="server" validationgroup="AddNew"></asp:textbox>
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator2" runat="server"
controltovalidate="txtImagedesc" errormessage="Please add the image description"
validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label3" runat="server">Image upload</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:fileupload id="FileUpload1" runat="server" allowmultiple="true" />
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator3" runat="server"
controltovalidate="FileUpload1" errormessage="Please add the gallery date" validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
Please suggest what to do in this case when uploading multiple images how to set different titles for different Images.
UPDATED CODE BEHIND
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Request.QueryString.Count > 0)
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename));
using (SqlConnection conn = new SqlConnection(conString))
if (Request.QueryString["Id"] != null)
{
string Id = Request.QueryString["Id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = " Update tbl_galleries_stack SET gallery_id=#gallery_id,img_title=#img_title,img_desc=#img_desc,img_path=#img_path, IsDefault=#IsDefault Where Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#gallery_id", ddlgallery.SelectedValue);
cmd.Parameters.AddWithValue("#img_title", txtImagetitle.Text);
cmd.Parameters.AddWithValue("#img_desc", txtImagedesc.Text);
cmd.Parameters.AddWithValue("#img_path", filename);
cmd.Parameters.AddWithValue("#IsDefault", chkDefault.Checked);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery updated sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_galleries_stack (gallery_id,img_title,img_desc,img_path,IsDefault) values(#gallery_id,#img_title, #img_desc, #img_path,#IsDefault)", conn);
cmd1.Parameters.Add("#gallery_id", SqlDbType.Int).Value = ddlgallery.SelectedValue;
cmd1.Parameters.Add("#img_title", SqlDbType.NVarChar).Value = txtImagetitle.Text;
cmd1.Parameters.Add("#img_desc", SqlDbType.NVarChar).Value = txtImagedesc.Text;
cmd1.Parameters.Add("#img_path", SqlDbType.NVarChar).Value = filename;
cmd1.Parameters.Add("#IsDefault", SqlDbType.Bit).Value = chkDefault.Checked;
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery added sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
}
There is no way you can give different title / description as you have given no option to provide it. Period.
You are forced to use multiple fileupload controls. This is also tricky because asp:FileUpload controls wont maintain their state after postback.
So, the solution I can see is a two-part one. Create two panels and hide the second panel at page load
Part 1
Place a label and textbox and button like this in the first panel in your page.
When the user enters a value, say 10, and fires EnterButton_click close Panel1 and open Panel2.
Part 2
On Panel 2, place a GridView like this
<asp:GridView ID="ImagesGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Sl No">
<ItemTemplate><%# Container.DisplayIndex + 1 %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:TextBox ID="txtTitle" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:FileUpload ID="flUpload" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="SaveButton" Text="Save" runat="server" OnClick="SaveButton_Click"/>
Now on the Enter buttons click event on Panel 1, write this.
// the idea is to create an empty gridview with number of rows client selected
protected void EnterButton_Click(object sender, EventArgs e)
{
//in this, 10 has been entered
var imageCount = Convert.ToInt32(txtImageCount.Text);
//var list = new List<string>();
//for (int i = 0; i < imageCount; i++)
//{
// list.Add(string.Empty);
//}
var list = new List<string>(10);
list.AddRange(Enumerable.Repeat(String.Empty, imageCount));
ImagesGrid.DataSource = list;
ImagesGrid.DataBind();
//TO DO: hide panel1 and make panel2 visible
}
So on clicking enter, you will get an empty gridview with ten rows.
Now fill the rows in the GridView, do validation and hit Save. On Save Button click event, you can access the WebControls like this.
protected void SaveButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in ImagesGrid.Rows)
{
var title = row.FindControl("txtTitle") as TextBox;
var description = row.FindControl("txtDescription") as TextBox;
var imageFile = row.FindControl("flUpload") as FileUpload;
string filename = Path.GetFileName(imageFile.FileName);
imageFile.SaveAs(Server.MapPath("/GalleryImages/" + filename));
//TO DO: write save routine
}
}
It looks like you only have one set of inputs tied to a single file upload with multiple turned on.
You will either want to turn off multiple and allow the user to add reported sets of those images, or have the editing of title, etc happen in a gridview with the upload.
You could also support a"holding cell " where they upload and then must enter that information before you actually save it to your data store.

How to Visible textbox from datalist

I want to visible and invisible my textbox and label from my datalist. My datalist is fulfill with checkboxes. so, i mean i have many checkbox that integrated to database.
I have 2 main data. 1 as the Header and 1 as the subHeader, every subHeader has many checkboxes called access. every access has id_access(i save it into HiddenField 'id_access') and every Header has id_jenis (i save it into HiddenField 'id_jenis_access'). if the access (checkbox text) show 'Others' (id_access = 'ACT5') and the Header show 'Others' (id_jenis = 'JO1') then the label Reaseon and Discribtion with their textbox will show up. but i have problem.
this is my form
<asp:DataList ID="DataListTest" runat="server" OnPreRender="PreTes">
<ItemTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label ID="lblHeader" runat="server"></asp:Label> <!-- Telephone, Bussines System -->
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblsubheader" runat="server" /></td> <!-- Oracle, EPM, CRM (Muncul di Form) -->
</tr>
<tr>
<td>
<asp:HiddenField ID="id_jenis_access" runat="server" Value='<%Eval(idJenisAccess) %>' /> <!-- Output = JT1, JO1, JBS1 (ID_JENIS) -->
<asp:HiddenField ID="subhd" runat="server" Value='<%# Eval("sub_jenis") %>' /> <!-- Oracle, EPM, CRM (nama sub jenis) -->
<asp:HiddenField ID="id_access" runat="server" Value='<%# Eval("id_access") %>' /><!-- Output = ACT5, ACBS1 -->
<asp:HiddenField ID="hd" runat="server" Value='<%# Eval("nama_jenis") %>' /><!-- Output = Telephone, Bussines System -->
</td>
</tr>
<tr>
<td>
<asp:CheckBox ID="cbCountryName" runat="server" Text='<%# Eval("nama_access") %>' /> <!-- Output = Local, Handphone, Project -->
<asp:TextBox ID="testme" runat="server" Text="" Visible="false" /> <!-- Output = Textbox for all -->
</td>
</tr>
<tr>
<td><asp:Label ID="lblReason" runat="server" Visible="false" text="Reason : "/>
<asp:TextBox ID="txtReason" Text="Reason" runat="server" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblDescription" runat="server" Visible="false" text="Description : "/>
<asp:TextBox ID="txtDescription" runat="server" Text="" Visible="false" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
this is my code to call all my data from database
private void ShowDataList()
{
conn.Open();
string sql = "Select access.id_access as 'id_access', access.nama_access, jenis_access.id_jenis_access as 'idJenisAccess' , "+
"jenis_access.nama_jenis_access as 'nama_jenis', sub_jenis.nama_sub_jenis as 'sub_jenis',sub_jenis.id_sub_jenis "+
"FROM access LEFT JOIN detil_access ON access.id_access = detil_access.id_access "+
"LEFT JOIN jenis_access ON detil_access.id_jenis_access = jenis_access.id_jenis_access "+
"LEFT JOIN sub_jenis ON detil_access.id_sub_jenis = sub_jenis.id_sub_jenis "+
"ORDER BY jenis_access.id_jenis_access";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
dt = new DataTable();
adp.Fill(dt);
DataListTest.DataSource = dt;
DataListTest.DataBind();
}
My problem is my lblReason, txtReason, lblDescribtion, and txtDescription is cannot show.
this is my code on PreRender datalist, i called it PreTes.
protected void PreTes(object sender, EventArgs e)
{
string temp = "";
string subtemp ="";
foreach (DataListItem item in DataListTest.Items)
{
Label objLabel = (Label)item.FindControl("lblHeader");
Label subjenis = (Label)item.FindControl("lblsubheader");
TextBox t = (TextBox)item.FindControl("testme");
CheckBox objName = (CheckBox)item.FindControl("cbCountryName"); // Internet, User Folder, etc (the Access)
HiddenField objHD = (HiddenField)item.FindControl("hd"); // Telephone, Busines System
HiddenField subobjHD = (HiddenField)item.FindControl("subhd"); // Oracle, CRM , EPM
HiddenField id_access = (HiddenField)item.FindControl("id_access"); // ACT5, ACBS1, etc (code Access)
HiddenField id_jenis = (HiddenField)item.FindControl("hdIdJenisAccess"); // JTO1, JBS1, etc (code Jenis)
TextBox tr = (TextBox)item.FindControl("txtReason");
TextBox td = (TextBox)item.FindControl("txtDescription");
Label lblReason = (Label)item.FindControl("lblReason");
Label lblDescription = (Label)item.FindControl("lblDescription");
if (temp != objHD.Value)
{
temp = objHD.Value;
objLabel.Text = temp + "<br/>";
}
if (subtemp != subobjHD.Value)
{
subtemp = subobjHD.Value;
subjenis.Text = subtemp + "<br/>";
}
if (id_access.Value == "ACT5" && id_jenis.Value == "JO1")
{
lblDescription.Visible = true;
td.Visible = true;
lblReason.Visible = true;
tr.Visible = true;
}
}
So, What should I do ?
FYI:i'm a newbie here and also c# programmer
after : HiddenField id_access = (HiddenField)item.FindControl("id_access");
add; var value_id_access = id_access.Text;
some things for other values

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! :)

Compare two tables in asp.net

I'm making a website to show various statistics regarding games.
I got two seperate tables in an sql-database. One called PlayerMatch and another called Match.
The two columns I want to compare is TeamId in PlayerMatch (PlayerMatch.TeamId vs. WinningTeamId in Match (Match.WinningTeamId)
To show it all, I have made a table, where I have placed some asp:repeaters inside.
Here is one of them, as they are all essentially the same.
<asp:Repeater ID="repHighGPM" runat="server">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%#Eval("Match.WinningTeamId") %></td>
<td><%#Eval("Name") %></td>
<td>
<img src=' <%#Eval("Image") %>' /></td>
<td><%#Eval("GoldPerMinute") %></td>
</ItemTemplate>
</asp:Repeater>
Now, the problem is that as it is now it will only show the Id of the team who won (Match.WinningTeamId). But not if the player was on that team. So essentially it just needs to check if PlayerMatch.TeamId == Match.WinningTeamId. And if that is true it should write "won match", while false will be "lost match"
Any ideas? I know it should be some kind of if-else function, but I have no idea how to do it.
You could use the inner join in sql query :
make a datasource to your databse write the query after that add the datasource to repeater DataSourceID="" ....
<asp:Repeater ID="repHighGPM" runat="server" DataSourceID="match">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%#Eval("Match.WinningTeamId") %></td>
<td><%#Eval("Name") %></td>
<td>
<img src=' <%#Eval("Image") %>' /></td>
<td><%#Eval("GoldPerMinute") %></td>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="match" runat="server" ConnectionString="<%$ ConnectionStrings:database %>" SelectCommand="select m.match number, m.winningTeamID, Name ,Image from Match m inner join
playermatch p on p.Teamid = m.WinningTeamId"></asp:SqlDataSource>
for more information about inner join read this article :
http://www.w3schools.com/sql/sql_join_inner.asp
I have solved the problem with the following solution:
public string MatchResult (object Result) {
int id = Convert.ToInt32(Request.QueryString["id"]);
DOTA2DataContext db = new DOTA2DataContext();
var Victory = Result;
var TeamId = db.PlayerMatches.Where(x => x.TeamId == id);
var WinningTeam = db.Matches.Where(x => x.WinningTeamId == id);
{
if (TeamId == WinningTeam)
{
return "Won match";
}
else
{
return "Lost match";
}
}
}
And the repeater.
<asp:Repeater ID="repHighD" runat="server">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%# MatchResult(Eval("Match.WinningTeamId"))%></td>
<td><%#Eval("Hero.Name") %></td>
<td>
<img src=' <%#Eval("Hero.Image") %>' /></td>
<td><%#Eval("Denies") %></td>
</ItemTemplate>
</asp:Repeater>

SQL Databinding to Dropdown Lists in Repeaters C#

Ok guys, so I am trying to bind data into a dropdown list from c#. I am getting a Null error when trying to enter the data into the DDL's. I am using this code for the front end.
<asp:Repeater ID="RepeaterHardDrives" runat="server">
<HeaderTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hidHardDrivesPackageDefaultID" runat="server" />
<asp:HiddenField ID="hidHardDrivesPackageDefaultPrice" runat="server" />
<span>
<asp:Label runat="server" ID="lbHardDiskPrice" Text="$00.00/mo"></asp:Label></span><label>Hard
Drive:</label><asp:DropDownList ID="ddHardDrive" DataTextField="ItemName" DataValueField="ProductItemID" runat="server" CssClass="lidropdown">
</asp:DropDownList>
<asp:ImageButton runat="server" ID="ShowHarddriveInfo" ImageUrl="/_Images/server_configurator_helpbutton.png"
OnClick="lnkShowHarddriveInfo_OnClick" /></div>
</td>
<td align="right">
<asp:Label runat="server" ID="lbHardDrivesPrice" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<br />
</FooterTemplate>
</asp:Repeater>
for the backend I am trying to load a dynamic number of Dropdown lists into the repeater then databind them all with the same data.
public void PopulateHardDrives(int intSupportedDrives)
{
PreloadHardDriveRepeater(intSupportedDrives);
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connstrname"].ConnectionString);
SqlCommand cmd = new SqlCommand("Prod_SelectIDNamePriceByCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CategoryCode", "Hard Drive");
DataTable dtHardDrives = new DataTable();
using (conn)
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dtHardDrives.Load(dr);
ViewState.Add("dtHardDrives", dtHardDrives);
}
foreach (RepeaterItem riHardDrive in RepeaterHardDrives.Items)
{
DropDownList ddHardDrives = (DropDownList)riHardDrive.FindControl("ddHardDrives");
ddHardDrives.DataSource = dtHardDrives;//program gives NULL exception error here(object not set to instance of object however it know the count of the rows it is supposed to be pulling)
ddHardDrives.DataValueField = "ProductItemID";
ddHardDrives.DataTextField = "ItemName";
ddHardDrives.DataBind();
Label lbHardDrive = (Label)riHardDrive.FindControl("lbHardDrivesPrice");
lbHardDrive.Text = String.Format("{0:c}", Convert.ToDecimal("0.00"));
if (riHardDrive.ItemIndex != 0) //We do not want to allow None to be selected on the main drive
{
ddHardDrives.Items.Insert(0, "None");
}
}
}
and last but not least the function to setup the dynamic amount of DDL's looks like this
private void PreloadHardDriveRepeater(int intSupportedDrives)
{
int[] intArrDisks = new int[intSupportedDrives];
for (int intDiskCount = 0; intDiskCount < intArrDisks.Length; intDiskCount++)
{
intArrDisks[intDiskCount] = intDiskCount;
}
RepeaterHardDrives.DataSource = intArrDisks;
RepeaterHardDrives.DataBind();
}
I am calling a list of populate functions in a !page.isPostBack if statement and the only one that is not getting the data is this one with the Drown Lists. It gets the number of Rows(18) from the database, but it it throwing a Null error(Object reference not set to an instance of an object.) I have seen quite a few people have been running into this error while googling the problem, however I could not find a solution that worked for me. The PreloadHardDriveRepeater function seems to work fine when run alone it loads the correct amount of DDL's onto the page.
Thanks ahead of time.
Your control is "ddHardDrive":
<asp:DropDownList ID="ddHardDrive" DataTextField="ItemName" DataValueField="ProductItemID" runat="server" CssClass="lidropdown">
and your code is looking for "ddHardDrives"
riHardDrive.FindControl("ddHardDrives");
This would be easy to notice if you debugged into the function and looked at your variable values right before the exception is thrown.

Categories

Resources