Search code examples
asp.netwebformsaspxgridview

if condition in aspx markup tag


How do I set the value of primaryKey attribute in a gridview aspx markup bases on condition?

<% 
string val=string.Empty;
if(Id=1){
%>
val="red";
<% else { %>
val="blue";
<%} %>

<GridView runat="server" id="someid" PrimaryKey=val />

Solution

  • Your code have issues, you need to fix that.

    Issue 1

    if(Id=1){ Not correct , it should be if(Id==1){

    Issue 2:

    Propriety should not be PrimaryKey it should be DataKeyNames

    Issue 3:

    <GridView runat="server" id="someid" PrimaryKey=val />
    

    It should be

     <asp:GridView runat="server" id="someid"  />
    

    Instead of using a variable and using that for setting, you can do it like following.

              <% 
                    string val = string.Empty;
                    if (Id == 1)
                    {
                        someid.PrimaryKey = "red";
                    }
                    else
                    {
                        someid.PrimaryKey = "blue";
                    }
                %>
                <asp:GridView runat="server" id="someid" />