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.
SqlCommandbut not using parameters, you really should use parameters for Sql queries, especially where the data comes from the client. Look at Step 3 in this article: msdn.microsoft.com/en-us/library/ff648339.aspx it's old but it still applies =] (Yes I know it's unlikely that someone is going to change the code in your page but you never know, especially if it's a public-facing website.)