CommandArgument is empty - asp.net

I would like to do this :
<asp:ImageButton runat="server" ID="addToCartIMG" OnCommand="btnAdd_Click" EnableViewState="false" CommandArgument='<%# itemId1.Value + ";" + Name1.Text %>' ImageUrl="<%$Resources:MasterPage, Image_AddToCart%>" />
where Item1 is hiddenField and Name1 a literal.
When I debug the method btnAdd_Click, the CommandEventArgs is empty and I don't understand why...
Thank you

You can't evaluate form field's values as you do in your example. If these values you try to evaluate are static, I mean doesn't change by your user's actions, you can pass them statically to your button's CommandArgument property.
If the values are changing by your user's actions, then you should get them at server-side by the reference of your controls like that :
string itemId = itemId1.Value;
// OR :
string itemId2 = Request.Forms["itemId1"];
For LiteralControl, you can't get it's text. you should turn it to form element.
Eval method is not a client-side function that passes your controls' values dynamically to server.

Related

Serve Tag not well formed when using EVAL() in OnClientClick event

I'm trying to create an onclick event like so
onClientClick="document.querySelector('[KPI="31"]').value = '';return false;"
The KPI= value has to be data bound, so I use code like so
onClientClick="<%# document.querySelector('[KPI=Eval("KPI_ID")]').value = '';return false; %>"
But I get an error saying the server code is not well defined. Could anyone help please..
If your datasource is a collection of objects and you are requesting a property called KPI_ID you can avoid using Eval and use Item or Container.DataItem.
Easiest way for me to show this is Container.DataItem, since I don't know what kind of control you are using to bind to. Container.DataItem should be your object, so you only need to cast it to your dataType
onClientClick="document.querySelector('[KPI=<%# ((YourDataType)Container.DataItem).KPI_ID %>)]').value = '';return false;"
If you use a Repeater in .Net 4.5 you can set the ItemType for the Repeater to your DataType so you can replace ((YourDataType)Container.DataItem) to Item:
onClientClick="document.querySelector('[KPI=<%# Item.KPI_ID %>)]').value = '';return false;"
If you are not using a property from an object and KPI_ID is a string to use to get the actual value, e.g. if it's in a DataRow, you have to avoid using " in the whole string, without letting the compiler know that it's not the end of the attribute. You can do that by using ' to indicate start and end of attribute and use string.Format so the single quote ' in your javascript is part of the text and the compiler knows it's not the end of the attribute:
onClientClick='<%# string.Format("document.querySelector('[KPI={0}]').value = '';
return false;", Eval("KPI_ID")) %>'
UPDATE:
To support the the additional double quote you can do:
onClientClick='<%# string.Format("document.querySelector('[KPI=\"{0}\"]').value = '';
return false;", Eval("KPI_ID")) %>'
You can replace Eval("KPI_ID") by Item.KPI_ID or ((YourDataType)Container.DataItem).KPI_ID if you wanna avoid using Eval.

ASP.NET - define a variable in an ASP page, then use it for a web control attribute's value

Is it possible in an ASP page to define a variable, then use that variable for a web control's attribute value?
I'm trying to add validation controls to my ASP.NET page, and one of them is a regex control. The expression I want will check that a field only contains numbers, spaces, plus sign and round brackets. (for phone numbers) Now round brackets are a special character that can't be escaped with a slash (as far as I can tell), so what I did was use Regex.Escape() to construct my regular expression, which I stored as a string variable. I now want to use that variable as the value for the regex validation control's expression attribute. Is this possible? If not, how can I achieve the validation I want?
EDIT1: So, in the tag of my ASP page I have this:
<% string PhoneNumber = "[^0-9 |^" + Regex.Escape("(") + " |^" + Regex.Escape(" "); %>
Then further down I have this:
<asp:RegularExpressionValidator ID="MobilePhoneValidator" runat="server" ControlToValidate="MobilePhone" ErrorMessage="Mobile phone number must only contain numbers." ForeColor="Red" ValidationExpression=PhoneNumber></asp:RegularExpressionValidator>
I'm pretty sure that using ValidationExpression="PhoneNumber" will use the actual string PhoneNumber and not look up my variable. Though to be honest, I haven't actually tried that.
I don't know why you spcified a string in markup rather than code behind, but anyway.
Assigning this string to your validator looks like this then:
<asp:RegularExpressionValidator ID="MobilePhoneValidator" runat="server" ControlToValidate="MobilePhone" ErrorMessage="Mobile phone number must only contain numbers." ForeColor="Red" ></asp:RegularExpressionValidator>
<% string PhoneNumber = "[^0-9 |^" + Regex.Escape("(") + " |^" + Regex.Escape(" ");
MobilePhoneValidator.ValidationExpression = PhoneNumber; %>
Or you could just define it in your code file, rather then markup.

Binding alias-named column to gridview in ASP.Net

I am using .Net 3.5. I have a site that I have been using gridview controls on. Basically, it is a standard gridview, but with AutoGenerateColumns turned off in favor of creating our own columns via ItemTemplate. Here is an example of one of our custom columns:
<asp:TemplateField HeaderText="Physician" ItemStyle-Width="70px" HeaderStyle-Width="70">
<ItemTemplate>
<asp:Label ID="lblPhysician" runat="server" Text='<%# Bind("LastName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
In code behind, I fill a datatable based on an SQL query, and set it as the gridview datasource, and the label is normally populated based on the Bind function seen above during Postback. However, I have a SQL query that utilizes Alias names now. The query is rather large but here is an example:
SELECT LastName, COUNT(Case WHEN <condition> THEN 1 END) AS ABC
FROM tablename WHERE <condition> Group By LastName
The problem is that I cannot use the Bind command on ABC as I use it for LastName. Nothing shows up in the gridview except LastName, even though data is returned for the alias columns. If I set AutoGenerateColumns to true, the gridview is binded with all the correct data, but this is not the way we need the page to work. What am I missing that is not allowing me to bind a column value manually to a control via it's alias name?
Thanks, and let me know if further clarification is needed!
You can grab it from the row on data bound; add an event handler, an in that handler do:
.. Grid_RowDataBound(..)
{
var abc = DataBinder.Eval(e.Item.DataItem, "ABC")
if (abc == null)
((Label)e.Item.FindControl("lblPhysician")).Visible = false;
}
There may be some syntaxes that are off but the gist is that you can extract the field from the data item, and do something with it programmably.
You could also bind it in the item template using a hidden field, or stick it in the DataKeys collection too.

Can I pass more than 2 parameters or an array with onCommand event in asp.net?

the question is above and it is short. I am trying to pass more parameters through a button in a repeater itemtemplate
I would append the values to a string with a delimeter, like this:
CommandArgument='<%# String.Format("{0}|{1}|{2}", Eval("Column1"), Eval("Column2"), Eval("Column3"))'%>
When you get into the event handler, just split the string at the delimeter, like this:
var columnList = e.CommandArgument.Split('|');
The CommandArgument property takes a string. So you could put several values into that property in a comma separated format, e.g:
button.CommandArgument = "param1,param2,param3";
Then in the OnClick event handler, simply split the CommandArgument property:
var parameters = e.CommandArgument.Split(',');
I used a dumb way to walk around this problem.
pass all the stuff into CommandArgument and use string.split to get the parameter array.
CommandArgument='<%# Eval("PersonId") + ";" + Eval("PersonName") %>'
string[] paras = argu.Split(';');

How do I deal with null or string.Empty when ASP.NET Repeater renders Binder.Eval Table TDs?

Here's my situtation. I have a Repeater bound to a List, which is rendering Table rows. I'm using <%# DataBinder.Eval(Container.DataItem, "SomeStringProperty")%> to display my data. The problem is that when the SomeStringProperty is null, string.Empty, or " " (some whitespace), the border for my TD is not getting rendered. Its as if its empty and quite ugly. I'm not sure how to handle this. Googling hasn't yielded the ans. Maybe someone here can tell me. Thanks..
I would replace the call to DataBinder.Eval with a Literal control and handle the Repeater's ItemDataBound event (OnItemDataBound). In the handler, check if the item is null and return a non-breaking space if it is.
You could also wrap the Eval in a method call for the same effect:
<%# CheckNull(Eval("SomeStringProperty")) %>
in the code behind:
protected string CheckNull(object value)
{
return string.IsNullOrEmpty(value) ? "SEE BELOW" : value.ToString();
}
I can't get this to display correctly -- SEE BELOW should be replaced with
You may need to compare the value to System.DBNull.Value in addition to string.IsNullOrEmpty if it's coming from a database.

Resources