How to access values where datasource is stored procedure - c#

This is my list view:
<asp:ListView ID="lstList" runat="server" OnItemDataBound="lstList_ItemDataBound"
OnPagePropertiesChanging="lstList_PagePropertiesChanging">
<LayoutTemplate>
<table border="1" cellpadding="2" cellspacing="0" id="Table1" runat="server"
class="TableCSS" style="width:100%;">
<tr id="Tr1" runat="server" class="TableHeader">
<td>Description</td>
</tr>
<tr id="ItemPlaceholder" runat="server"></tr>
<tr id="Tr2" runat="server">
<td id="Td7" runat="server" align="right" colspan="5" class="TableData">
<asp:DataPager ID="lvDataPager1" runat="server"
PagedControlID="lstList" PageSize="6">
<Fields>
<asp:NumericPagerField ButtonType="Link" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<EmptyDataTemplate>No match</EmptyDataTemplate>
<ItemTemplate>
<tr class="TableData">
<td><asp:Label ID="lblDescription" runat="server"/></td>
</tr>
</ItemTemplate>
</asp:ListView>
The datasource of listview is set by dbml stored procedure. The function which binds the listview is
public List<sp_ListResult> GetList(byte id)
{
List<sp_ListResult> results = new List<sp_ListResult>();
var en = dataContext.dc.sp_List(id).GetEnumerator();
while (en.MoveNext())
{
results.Add(en.Current);
}
return results;
}
lstList.DataSource = GetList(id);
I want to get the description value and set it to listview label but am not able to do it.
protected void lstList_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
//Get the item object.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
// throws error System.InvalidCastException: 'Unable to cast object
DataRowView rowView = e.Item.DataItem as DataRowView;
String description = rowView["Description"].ToString();
}
}

You are not binding a DataTable but a List<class>, so you have to convert to the right type.
sp_ListResult rowView = e.Item.DataItem as sp_ListResult;

Related

Add the values inside (labels) together that are inside (list view)

How can I add the values inside the labels created in (List View) together?
And show the values added together in a label
<asp:Label ID="lbl_Plural" runat="server" Text="0">
You can just bind the list view, and then loop each row, and get the total.
Say I have this listview:
<h2>Fighter Prints</h2>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:Label ID="Fighter" runat="server" Text='<%# Eval("Fighter") %>' /></td>
<td><asp:Label ID="Engine" runat="server" Text='<%# Eval("Engine") %>' /></td>
<td><asp:Label ID="Thrust" runat="server" Text='<%# Eval("Thrust") %>' /></td>
<td><asp:Label ID="Description" runat="server" Text = '<%#Eval("Description") %>' /></td>
<td>
<asp:Image ID="iPreview" runat="server" Height="68px" Width="149px"
ImageUrl='<%# Eval("ImagePath") %>'/>
</td>
<td><asp:TextBox ID="Qty" runat="server" Text='<%# Eval("Qty") %>' Width="30px"/></td>
<td><asp:Label ID="Price" runat="server" Text='<%# string.Format("{0:c2}",Eval("Price")) %>'/></td>
<td><asp:Label ID="Total" runat="server" Text='<%# string.Format("{0:c2}",Eval("Total")) %>'/></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" style="" class="table table-hover">
<tbody>
<tr runat="server" style="" >
<th runat="server">Fighter</th>
<th runat="server">Engine</th>
<th runat="server">Thrust (lbs)</th>
<th runat="server">Description</th>
<th runat="server">Preview</th>
<th runat="server">Qty</th>
<th runat="server">Price</th>
<th runat="server">Total</th>
</tr>
<tr id="itemPlaceholder" runat="server" />
</tbody>
<tfoot>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td><td>Total</td>
<td><asp:Label ID="MyTotal" runat="server" Text="0"></asp:Label></td>
</tr>
</tfoot>
</table>
</LayoutTemplate>
</asp:ListView>
Now, in above, I did put in a total footer, but it could have been any control or lable on the page that I stuff the results into.
So, the code to do this?
Bind the ListView
Loop the total, and then put the value into a label, text box, or in this case a label at the footer of the list view.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
conn.Open();
DataTable rstData = new DataTable("Fighters");
rstData.Load(cmdSQL.ExecuteReader());
rstData.Columns.Add("Total", typeof(decimal),"[Qty] * [Price]");
ListView1.DataSource = rstData;
ListView1.DataBind();
decimal myTotal = 0;
foreach (ListViewItem OneRow in ListView1.Items)
{
Label MyPrice = OneRow.FindControl("Total") as Label;
myTotal += Decimal.Parse(MyPrice.Text, NumberStyles.Currency);
}
// now update the final total label
Label lblTotal = ListView1.FindControl("MyTotal") as Label;
lblTotal.Text = string.Format("{0:c2}", myTotal);
}
}
}
Results:

Listview Returning EmptyDataTemplate when Dataset shrinks but still has records

I am able to successfully bind a ListView with no query criteria that returns 100 records. The ListView has a DataPager with a pagesize of 10. If I change the criteria of the query to reduce the number of records to, let's say 55, one of two things happens:
If I'm on page 1 through 6 of the initial ListView then the new ListView populates correctly.
If I'm on page 7 or greater, the ListView returns an EmptyDataTemplate even though there are records present (I can see this in the DataSet in VS).
Re #2, the desired behavior is for it to go to page 1.
.CS
protected void bindfindListView()
{
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
string criteria = "";
if (ddl.SelectedValue == "1" && !String.IsNullOrEmpty(txt.Text))
{
criteria = " AND CONTAINS(transactions.[blah], '\"*" + txt.Text + "*\"')";
}
SqlCommand cmdaccount = new SqlCommand("SELECT DISTINCT id, name, blah FROM nah.dbo.items WHERE email=#userstr" + criteria + " GROUP BY id, name, blah", conn);
cmdaccount.Parameters.AddWithValue("#userstr", Session["user"].ToString());
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(cmdaccount);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
findlv.DataSource = myDataSet;
findlv.DataBind();
Session["findds"] = myDataSet;
conn.Close();
}
protected void findlv_DataBound(object sender, EventArgs e)
{
if (findlv.Items.Count > 0)
{
DataPager pager = (DataPager)findlv.FindControl("findpager");
if (pager != null)
{
pager.Visible = (pager.PageSize < pager.TotalRowCount);
}
}
}
protected void findlv_PagePropertiesChanged(object sender, EventArgs e)
{
bindfindListView();
}
.aspx
<asp:ListView ID="findlv" runat="server" OnDataBound="findlv_DataBound" OnPagePropertiesChanged="findlv_PagePropertiesChanged" Visible="true">
<LayoutTemplate>
<table class="results" id="tblresults">
<tr>
<th class="tdpadleft col170">Property Address</th>
<th class="col170">Property Name</th>
<th class="col170">Seller/Landlord</th>
<th class="col170">Buyer/Tenant</th>
<th class="col78">Status</th>
<th class="col100">Last Update</th>
<th class="col50">Delete</th>
</tr>
<tr id="itemPlaceholder" runat="server"></tr>
</table>
<div class="pager2">
<asp:DataPager ID="findpager" runat="server" PageSize="10" PagedControlID="findlv">
<Fields>
<asp:NextPreviousPagerField ShowNextPageButton="False" ButtonCssClass="previousNextLink" />
<asp:NumericPagerField ButtonCount="10" ButtonType="Link" NumericButtonCssClass="numericLink" />
<asp:NextPreviousPagerField ShowPreviousPageButton="False" ButtonCssClass="previousNextLink" />
<asp:TemplatePagerField>
<PagerTemplate>
<div class="pagertotal">
Showing
<asp:Label runat="server" ID="CurrentPageLabel" Text='<%# Container.StartRowIndex + 1 %>' />
to
<asp:Label runat="server" ID="TotalPagesLabel" Text='<%#(Container.StartRowIndex+Container.PageSize) > Container.TotalRowCount ? ((Container.StartRowIndex+Container.PageSize)-((Container.StartRowIndex+Container.PageSize)-Container.TotalRowCount)) : (Container.StartRowIndex+Container.PageSize) %>' />
(of
<asp:Label runat="server" ID="TotalItemsLabel" Text='<%# Container.TotalRowCount%>' />
records)
</div>
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
<ItemTemplate>
<tr class="altRow rowcolor">
<td>
<asp:Label runat="server" ID="lblid" Text='<%#((DataRowView)Container.DataItem)["id"] %>' />
</td>
<td>
<asp:Label runat="server" ID="lblname" Text='<%#((DataRowView)Container.DataItem)["name"] %>' />
</td>
<td>
<asp:Label runat="server" ID="lblblah" Text='<%#((DataRowView)Container.DataItem)["blah"] %>' />
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<table id="empty">
<tr>
<td id="tdempty">No Transactions Found
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:ListView>

unable to access table back color property

For some reason in the C# code behind for asp.net, i cannot call the table by it's ID to set it's back color property. I tried and and nothing seems to work
Here is my asp.net table tag:
<table id="ptbl" runat="server" cellpadding="2" width="640px" border="1">
here is something similar to what i what to do in the C# code behind but it does not recognize the id
ptbl.Attributes.Add("style", "background-color:red")");
Any ideas/suggestions?
Update: here is the code. There is a layout template in it so somehow it can't see the table id, but if I take that out of it then it sees it. What can i do. I need the listview to get the data
<asp:ListView ID="ListView1" runat="server" Style="color: white; font-weight: bold">
<LayoutTemplate>
<table id="ptbl" runat="server" cellpadding="2" width="640px" border="1" style="color: black; font-weight: bold">
<tr runat="server">
<th runat="server">Ps</th>
<th runat="server">P</th>
<th runat="server">T</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager runat="server" ID="ContactsDataPager" PageSize="90">
<Fields>
<asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true"
FirstPageText="|<< " LastPageText=" >>|"
NextPageText=" > " PreviousPageText=" < " />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="Label1" runat="server"><%# Eval("Ps") %></asp:Label></td>
<td>
<asp:Label ID="Label2" runat="server"><%# Eval("P") %></asp:Label></td>
<td>
<asp:Label ID="Label3" runat="server"><%# Eval("T") %></asp:Label></td>
</tr>
</ItemTemplate>
</asp:ListView>
Again the layout template is causing the issue. how can i use the listview and the table with the layout template. I know this has morphed a bit now , but any help would be appreciated.
You cannot access the ptbl table until DataBind() has been called on ListView1. After it has been called and there is data in the dataset, then you can reference the the ptbl table like this:
protected void Page_Load(object sender, EventArgs e)
{
var tbl = new DataTable();
tbl.Columns.Add("Ps", typeof(Int32));
tbl.Columns.Add("P", typeof(string));
tbl.Columns.Add("T", typeof(string));
var r = tbl.NewRow();
r[0] = 99;
r[1] = "Hey";
r[2] = "USA";
tbl.Rows.Add(r);
ListView1.DataSource = tbl;
ListView1.DataBind();
var ptbl = (HtmlTable)ListView1.FindControl("ptbl");
ptbl.Style.Add("background-color", "red");
}

How do I get 'tr's ID with checkbox checked in code behind using C#

I got some problem and let me spend some time on testing.
I have a ListView , and a checkbox inside this, and a button outside.
When I click button , will show the rows Tr ID that rows checkbox checked.
but it always show ctrl2 instead of ID.
This is my code:
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<table cellspacing="0" border="0">
<tr>
<th scope="col" width="125">Man
</th>
<th scope="col" width="50">Type
</th>
<th scope="col" width="400">Reason
</th>
<th scope="col" width="125">date
</th>
<th scope="col" width="100">cheack
</th>
<th scope="col" width="125">remark
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="<%#Eval("ID").ToString()%>" runat="server">
<td scope="col" >
<%#Eval("UserID").ToString()%>
</td>
<td scope="col">
<%#Eval("Purpose").ToString() %>
</td>
<td scope="col">
<%#Eval("Reason").ToString() %>
</td>
<td scope="col">
<%#dateSession(Convert.ToDateTime( Eval("startTime"))) %>
</td>
<td scope="col">
<asp:CheckBox ID="CheckBox1" runat="server" Checked="True" />
</td>
<td scope="col">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
This is my code behind
protected void Btn_save_Click(object sender, EventArgs e)
{
foreach (ListViewItem row in this.ListView1.Items)
{
CheckBox stylistcheck = (CheckBox)row.FindControl("CheckBox1");
if (stylistcheck.Checked == true)
{
Response.Write(row.ID);
// Always get wrong ID , like 'ctrl3' not real rows Tr ID
}
}
}
Doing this <tr id="<%#Eval("ID").ToString()%>" runat="server"> will throw an error, AFAIR. If your goal is to get the ID for each row that represents your data then you can just add a literal control, hide it, and get it's value in code-behind. Something like:
<tr runat="server">
<td scope="col" >
<%# Eval("UserID").ToString()%>
<asp:Literal ID="idLiteral" runat="server" Text='<%# Eval("ID").ToString()%>' Visible="false" ></asp:Literal>
</td>
...rest of your code goes here...
</tr>
In code-behind, inside your if (stylistcheck.Checked == true) do a Response.Write(((Literal)row.FindControl("idLiteral")).Text); like so:
if (stylistcheck.Checked == true)
{
Response.Write(((Literal)row.FindControl("idLiteral")).Text);
}
CheckBox1.Checked = true;
It may help you.
OR
CheckBox chkDelete = (CheckBox)item.FindControl("CheckBox1");
if(chkDelete.Checked)
{
string yourID = item.DataItem["id"].ToString();
itemsToDelete.Add(yourID);
}
OR
if (CheckBox1.Checked==true)
{
}
This may also work for you.
yourListView.DataSource = GetCourses();
yourListView.DataBind();
var checkBox = yourListView.Controls.Cast<Control>).First().FindControl("yourID")
or
if (item.ItemType == ListViewItemType.DataItem){
CheckBox final = (CheckBox)item.FindControl("yourID");
if (final.Checked) {
}
Just wondering are you sure you can run this code ?
<tr id="<%#Eval("ID").ToString()%>" runat="server">
I tried your code and run it will encounter error on this line...
Because with " you will get error server tag is not well formed.
If i use this ' the error will be :
The ID property of a control can only be set using the ID attribute in the tag and a simple value.
I write the code which will retrieve ID might help you...
.aspx
<asp:ListView ID="ListView1" runat="server" >
<LayoutTemplate>
<table id="tbllol" runat="server" cellspacing="0" border="0">
<tr>
<th scope="col" width="100">cheack
</th>
<th scope="col" width="125">remark
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td scope="col">
<asp:CheckBox ID="chkBox" runat="server" Checked="true" />
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' Visible="false"></asp:Label>
</td>
<td scope="col">
<asp:TextBox ID="txtRemarks" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btn" runat="server" Text="Save" OnClick="btn_Click" />
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("ID");
// Loop & Add ID
for (int i = 0; i < 10; i++) dt.Rows.Add("myIDIi" + i);
ListView1.DataSource = dt;
ListView1.DataBind();
}
}
protected void btn_Click(object sender, EventArgs e)
{
// Variable
string value = string.Empty;
// Loop
foreach (ListViewItem row in ListView1.Items)
{
// Find Control
CheckBox chkbox = row.FindControl("chkBox") as CheckBox;
Label lblID = row.FindControl("lblID") as Label;
// Check & Check Then Set to Value
if (chkbox != null && chkbox.Checked)
if (lblID != null) value += lblID.Text.Trim() + "<br />";
}
Response.Write(value);
}

Get Data Value From ListView ItemDataBound

I'm sure I've done this before but really cant remember how.
In the ItemDataBound event of a ListView I need to get the actual data value. I cant seem to find it in the ListViewItemEventArgs object that gets passed in.
Thanks
Use the ListViewDataItem in the ItemDataBound event:
protected void yourListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
YourDataSource yourDataSource= (YourDataSource )dataItem.DataItem;
}
}
I think what you're after is the ListViewDataItem.DataItem
protected void Score_ItemDataBound(object sender, Telerik.Web.UI.RadListViewItemEventArgs e)
{
if (e.Item is RadListViewItem)
{
RadListViewDataItem item = e.Item as RadListViewDataItem;
object dataItem = ((System.Data.DataRowView)(((RadListViewDataItem)e.Item).DataItem)).Row.ItemArray[2].ToString();
string raetest = Convert.ToString(dataItem);
}
}
<asp:ListView ID="ContactsListView"
DataSourceID="ContactsDataSource"
ConvertEmptyStringToNull="true"
OnItemDataBound="ContactsListView_ItemDataBound"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="680px" border="0">
<tr style="background-color: #ADD8E6" runat="server">
<th runat="server">First Name</th>
<th runat="server">Last Name</th>
<th runat="server">E-mail Address</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager runat="server" ID="PeopleDataPager" PageSize="12">
<Fields>
<asp:NumericPagerField ButtonCount="10" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #CAEEFF" runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%#Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%#Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="EmailAddressLabel" runat="server" Text='<%#Eval("EmailAddress") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Server side
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// Display the e-mail address in italics.
Label EmailAddressLabel = (Label)e.Item.FindControl("EmailAddressLabel");
// EmailAddressLabel.Font.Italic = true;
string valueoftheControl = EmailAddressLabel.Text;
/* you have to get the value like this.
If its a dropdown or any other use their
corresponding property to get the value.*/
}
}

Categories

Resources