My e.CommandArgument is returning "" Every Time - c#

Whenever I click one of the delete linkbuttons, the e.CommandArgument always retains the value of "". I was reading somewhere that you can't use <%# in Command Arguments but I have seen several examples were this has worked. Any suggestions?
In ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:Label ID="dataLabel" runat="server" Text='<%# Eval("data") %>' />
<br />
<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
|
<asp:Label ID="Column1Label" runat="server" Text='<%# Eval("Column1") %>' />
<br />
<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<LoggedInTemplate>
<asp:LinkButton CLASS="DeleteButton" runat="server" OnCommand="Delete" CommandArgument='<%# Eval("id") %>' ViewStateMode="Disabled">Delete</asp:LinkButton>
</LoggedInTemplate>
</asp:LoginView>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [id],[name], [data], convert(varchar, [date], 101) FROM [Announcements] ORDER BY [date] DESC">
</asp:SqlDataSource>
IN ASPX.CS
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
SqlCommand command = conn.CreateCommand();
command.CommandText = "DELETE FROM Annoucnements WHERE id=#id";
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add(new SqlParameter("id", e.CommandArgument));
conn.Open();
command.ExecuteNonQuery();
}
As suggested by Royi Namir, changing EnableViewState to true fixed the problem.

After looking around for a little bit, I have found a few posts that say you can't use the <%# ... %> syntax inside server tags, which is clearly wrong as you are using it for the Text property and I'm sure I've done this exact same thing before. Anyway, you can use the ItemDataBound event on your DataList:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<asp:Label ID="dataLabel" runat="server" Text='<%# Eval("data") %>' />
<br />
<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
|
<asp:Label ID="Column1Label" runat="server" Text='<%# Eval("Column1") %>' />
<br />
<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<LoggedInTemplate>
<asp:LinkButton CssClass="DeleteButton" runat="server" ID="lbDelete" OnCommand="Delete" CommandArgument='<%# Eval("id") %>' ViewStateMode="Disabled">Delete</asp:LinkButton>
</LoggedInTemplate>
</asp:LoginView>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [id],[name], [data], convert(varchar, [date], 101) FROM [Announcements] ORDER BY [date] DESC">
</asp:SqlDataSource>
Notice I've added ID="lbDelete" to your LinkButton (and also changed CLASS to CssClass for you) which is needed to find the control in our code behind:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) // this is to ensure that we're looking in an item that will contain controls, and not the header or footer
{
LoginView headLoginView = (LoginView)e.Item.FindControl("HeadLoginView") // FindControl is not recursive so we need a reference to a control we can look in to find the button
LinkButton lbDelete = (LinkButton)headLoginView.FindControl("lbDelete");
if (lbDelete != null) // check for a null otherwise this code will fail if the user is not logged in, because the controls inside the LoggedInTemplate will not be rendered
{
lbDelete.CommandArgument = DataBinder.Eval(e.Item.DataItem, "id").ToString(); // set the CommandArgument on the button using DataBinder.Eval
}
}
}

You simply need the DataKeyField to uniquely identify your row in order to perform Delete operations.

Related

I am getting an error while passing query string of url between two pages

I am working on a project in which on first page that is default.aspx page I am having a grid view which is bind with a column categoryname of table category. Here is code default.aspx :
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="catid"
DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="catid" DataNavigateUrlFormatString="~/subcategory.aspx?catid={0}"
DataTextField="categoryname" />
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ToursandTravelsConnectionString %>"
SelectCommand="SELECT [catid], [categoryname] FROM [category]"></asp:SqlDataSource>
</form>
Now I am having a page named as subcategory.aspx which is having a label for subcategory name then its respective image and vice versa which is retrieved from table subcategory.Here is my code of subcategory.aspx
protected void Page_Load(object sender, EventArgs e)
{
labelsubcatname.Text = HttpUtility.UrlDecode(Request.QueryString["catid"]);
}
The problem is that when I am having catid I am getting the value as 1,2 and so on but when I am having subcatname retrieved from table subcategory which is as follows :
Image of table subcategory
Its does not shows subcatname from subcategory table. How to get the value of subcategory instead of catid?
I also want to display the image based on subcategory name which I have showed up in a grid view. I am getting all images for now this is my code for its grid view
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="labelsubcatname" runat="server"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="pic" SortExpression="pic">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("pic") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="200px"
ImageUrl='<%# Eval("pic") %>' Width="250px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="labelviewdetail" runat="server" Text="View Detail"></asp:Label>
<br />
</td>
</table>
</div>
</form>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ToursandTravelsConnectionString %>"
SelectCommand="SELECT [pic] FROM [subcategory]"></asp:SqlDataSource>
You can use inner join to your query in your DataSource so that you can get your subcatname from subcategory table, like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ToursandTravelsConnectionString %>"
SelectCommand="SELECT C.[catid], C.[categoryname], S.[subcatname] FROM [category] C INNER JOIN subcategory S ON C.[catid] = S.[catid]"></asp:SqlDataSource>
Then use subcatname in your hyperlinkfield:
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="subcatname" DataNavigateUrlFormatString="~/subcategory.aspx?subcatname={0}"
DataTextField="categoryname" />
</Columns>
Then you can get it from the query string:
labelsubcatname.Text = Request.QueryString["subcatname"] != null
? Request.QueryString["subcatname"].ToString()
: "N/A";
You have your Subcatid in page load of subcategory.aspx. Then using Subcatid to retrieve row value from database.
OK , Listen
DataNavigateUrlFormatString="~/subcategory.aspx?catid={0}"
means you are passing element 0 from data base i.e
Change it to 1 i.e
DataNavigateUrlFormatString="~/subcategory.aspx?catid={1}"
and you dont need
HttpUtility.UrlDecode(Request.QueryString["subcatname"]);'
Just replace it by
Request.QueryString["subcatname"].ToString();

asp.net button inside a datalist to go to another webpage

I need the button inside the datalist to open another page. However the response.redirect does not work !
here is the html
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<div id="content">
<!-- Review -->
<div class="products">
<h3>My Books</h3>
<h4>Items you have purchased</h4>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"></asp:SqlDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Width="618px" Height="114px">
<ItemTemplate>
<asp:Label ID="bookid" runat="server" Text='<%# Eval ("BookID") %>' Visible=" false"></asp:Label>
<asp:Label ID="bookname" runat="server" Text='<%# Eval ("Title") %>'></asp:Label>
<asp:Button ID="review" runat="server" Text="Review" CommandName="review" />
</ItemTemplate>
</asp:DataList>
<br />
</div>
</div>
below is the cs file
public void DataList1_ItemCommand(Object source, DataListCommandEventArgs e)
{
if (e.CommandName == "review")
{
DataList1.SelectedIndex = e.Item.ItemIndex;
Label bookid = (Label)DataList1.SelectedItem.FindControl("Bookid");
Response.Redirect("Review.aspx");
}
}
You still need to attach ItemCommand event to DataList1.
<asp:DataList OnItemCommand="DataList1_ItemCommand" ...>
...
</asp:DataList>
Try Server.Transfer("Review.aspx", true);

Get the element from itemTemplate in gridview asp.net

I want to ask a question, I'm actually looking for a way to modify the status of a textbox in my gridview, I'm quite lost since I just started this language a few weeks ago and i can't find a satisfying answer (maybe I apply them the wrong way maybe you will be able to help me there. Here is my code :
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="centrer">
<asp:Image ID="IMG_attente" runat="server" ImageUrl="~/Images/1px.gif" Height="32px" />
</div>
<asp:Panel ID="panListes" runat="server" Visible="false" CssClass="formulaire">
<asp:Label runat="server" ID="LabelErreur" Visible="false"></asp:Label>
<asp:GridView ID="ListePieceFlash" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceListePieceFlash"
OnRowEditing="ListePieceFlash_RowEditing" OnRowCancelingEdit="ListePieceFlash_RowCancelingEdit"
EnableModelValidation="True" SkinID="Source_DarkBlue" AllowPaging="True" DataKeyNames="NumOF"
OnRowCommand="ListePieceFlash_RowCommand" Width="100%" AllowSorting="True">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/Images/annuler.gif" CommandName="cancel"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ToolTip="Annuler" />
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/okvert.gif" CommandName="save"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ToolTip="Sauvegarder" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/Images/edit.png" CommandName="edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ToolTip="Sélectionner" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="NumSerieLabel" runat="server" Text="NumSerie"></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="NumSerie" runat="server" OnTextChanged="OnNumSerieChanged" /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="SymboleLabel" runat="server" Text="Symbole"></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="Symbole" runat="server" Enabled="False" OnTextChanged="OnSymboleChanged" /></ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceListePieceFlash" runat="server" ConnectionString="<%$ ConnectionStrings:PRMConnectionString %>"
SelectCommand="exec [dbo].[getListePieceFlash]"></asp:SqlDataSource>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
As you can see my "Symbole" TextBox is disabled at start but I want it to be enabled when i fill the first one and there is more than one element, here is the code behind (the SQL part is a stored procedure):
protected void OnNumSerieChanged(object sender, EventArgs e)
{
numSerieValue = (sender as TextBox).Text;
var con = Sql.Instance.ObtenirConnexionSql();
SqlCommand cmd = ObtenirCommande(con);
cmd.CommandText = "dbo.getListPiece";
Int32 count = (Int32)cmd.ExecuteScalar();
if (count > 1)
(ListePieceFlash.FindControl("Symbole") as TextBox).Enabled = true;
}
The problem is on the last line and I don't really know how to get over it actually, can someone help me? Thank you very much :)
ListePieceFlash.FindControl("Symbole") returns null because you cannot find the TextBox via GridView.FindControl. The NamingContainer of the TextBox is the GridViewRow.
You get it by casting the Sender in OnNumSerieChanged to TextBox and it's NamingContainer property to GridViewRow. Then use row.FindControl("Symbole") to find the target TextBox:
protected void OnNumSerieChanged(object sender, EventArgs e)
{
TextBox NumSerie = (TextBox) sender;
GridViewRow row = (GridViewRow) NumSerie.NamingContainer;
TextBox Symbole = (TextBox) row.FindControl("Symbole");
// ...
}
Note that i strongly advise against such helper classes in ASP.NET which hold and return database objects like your Sql.Instance.ObtenirConnexionSql(). It can be a source of nasty errors.

BulletedList in Reapeter

I Have a 2 tables in database w/c are connected
tblPackage
id Name
1 Package A
2 Package B
tblDetails
id PackageID Details
1 1 PackageDetails11
2 1 PackageDetails12
3 1 PackageDetails13
4 1 PackageDetails14
5 2 PackageDetails21
6 2 PackageDetails22
7 2 PackageDetails23
Now i want it to manipulate it on a repeater
HTML
<asp:Repeater ID="rptrPackage" runat="server">
<ItemTemplate>
<asp:Label id="Pack" runat="server" Text='<%# Bind("Pack") %>'></asp:Label>
<asp:BulletedList id="Details" runat="server">
</asp:BulletedList>
</ItemTemplate>
</asp:Repeater>
ASP
private void Populate()
{
DataTable dtPackage = tblPackage();
DataTable dtDetails = tblDetails();
rptrPackage.DataSource = dtPackage;
rptrPackage.DataBind();
}
Try this
aspx
<asp:Repeater ID="rptrPackage" runat="server">
<ItemTemplate>
<asp:Label ID="Pack" runat="server" Text='<%# Bind("Pack") %>'></asp:Label>
<asp:HiddenField ID="hID" Value='<%# Eval("PackageID") %>' runat="server" />
<asp:Repeater runat="server" ID="rptDetails">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<%# Eval("Details")%>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
code behind
private void Populate()
{
DataTable dtPackage = tblPackage();
DataTable dtDetails = tblDetails();
rptrPackage.DataSource = dtPackage;
rptrPackage.DataBind();
foreach (RepeaterItem item in rptrPackage.Items)
{
Repeater rptDetails = ((Repeater)item.FindControl("rptDetails"));
rptDetails.DataSource = dtDetails.Select("PackageID = " + ((HiddenField)item.FindControl("hID")).Value).CopyToDataTable();
rptDetails.DataBind();
}
}
Using SqlDataSourse inside repeater ,
<asp:Repeater ID="rptrPackage" runat="server" >
<ItemTemplate>
<asp:HiddenField ID="PackID" runat="server" Value='<%# Eval("id") %>'
/>
<asp:Label id="Pack" runat="server" Text='<%# Eval("Name") %>'></asp:Label><br/>
<asp:BulletedList ID="Details" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Details"
DataValueField="id">
</asp:BulletedList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT * FROM [tblDetail] WHERE [PackageID] = #PID" >
<SelectParameters>
<asp:ControlParameter Name="PID" Type="Int32" ControlID="PackID" PropertyName="Value" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:Repeater>

ASP.net Display Image from SQL

Solved: I used handlers. Thanks btw.
http://www.aspdotnetcodes.com/Insert_Images_Database.aspx
How can I display my image inside the DataList1?
I don't have a clear idea of databinding and such. I hope you guys can help. Thanks
This is my code for my ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
itemID:
<asp:Label ID="itemIDLabel" runat="server" Text='<%# Eval("itemID") %>' />
<br />
Cloth ID:
<asp:Label ID="Cloth_IDLabel" runat="server" Text='<%# Eval("[Cloth ID]") %>' />
<br />
Style:
<asp:Label ID="StyleLabel" runat="server" Text='<%# Eval("Style") %>' />
<br />
Size:
<asp:Label ID="SizeLabel" runat="server" Text='<%# Eval("Size") %>' />
<br />
Color:
<asp:Label ID="ColorLabel" runat="server" Text='<%# Eval("Color") %>' />
<br />
Image 1:
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("[Image 1]") %>' />
<br />
Image 2:
<asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("[Image 2]") %>' />
<br />
Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />
<br />
Notes:
<asp:Label ID="NotesLabel" runat="server" Text='<%# Eval("Notes") %>' />
<br />
Alignment of Image 1:
<asp:Label ID="Alignment_of_Image_1Label" runat="server"
Text='<%# Eval("[Alignment of Image 1]") %>' />
<br />
Alignment of Image 2:
<asp:Label ID="Alignment_of_Image_2Label" runat="server"
Text='<%# Eval("[Alignment of Image 2]") %>' />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TPSConnectionString %>"
SelectCommand="SELECT CustomizedOrder.userid, CustomizedOrder.itemID, ClothInventory.clothID AS [Cloth ID], ClothInventory.style AS Style, ClothInventory.size AS Size, Color.color AS Color, CustomizedOrder.image1 AS [Image 1], CustomizedOrder.image2 AS [Image 2], CustomizedOrder.itemPrice AS Price, CustomizedOrder.notes AS Notes, Alignment.description AS [Alignment of Image 1], Alignment_1.description AS [Alignment of Image 2] FROM CustomizedOrder INNER JOIN ClothInventory ON CustomizedOrder.clothID = ClothInventory.clothID INNER JOIN Color ON ClothInventory.colorID = Color.colorID INNER JOIN Alignment ON CustomizedOrder.alignment1 = Alignment.alignmentID INNER JOIN Alignment AS Alignment_1 ON CustomizedOrder.alignment2 = Alignment_1.alignmentID WHERE (CustomizedOrder.userid = #userid)">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>
and this is for the aspx.cs
public partial class addtoShoppingCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser User = Membership.GetUser();
object UserGUID = User.ProviderUserKey;
SqlDataSource1.SelectParameters.Add("userid", UserGUID.ToString());
SqlDataSource1.DataBind();
}
}
Asp:Image.ImageUrl expects an URL value, hence if Image1 is a string containing the URL of the image your code should work.
On the contrary, if Image1 is the image itself, then you'll need to temporarily save it on the server and provide the Asp:Image control with the URL for the saved file (check this example for generating the URL)
if you don't have image url from database and you have image datatype in your sql then this code will help to generate image from sql database!
If image path stored in database: ~/Images/file-name.jpg
=> image url in datalist:
ImageUrl='<%# Eval("[ImagePath]") %>' />

Categories

Resources