locked
Convert integer to String in Gridview RRS feed

  • Question

  • I have a gridview on webpage that is linked to a sql database. one of the columns in the database is JurisdictionID and the label for the column for this data is labeled as Jurisdiction.  I want to convert the numbers in this column to text.  Example: JuridictionID 99 should display as "Dispatch in the gridview, JurisdicitionID 48 should display at "Test2" and JurisdictionID 65 should display as "Test3".  The script I wrote will not work.  What am I doing wrong?
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
    
                    Label type = (Label)e.Row.FindControl("Jurisdiction"); if (type.Text == "99")
                    {
    
                        type.Text = "Dispatch";
                    }
    
                    else if (type.Text == "48")
                    {
    
                        type.Text = "Test2";
                    }
    
                    else if (type.Text == "65")
                    {
    
                        type.Text = "Test3";
                    }
                }
            }
        }
    }

    Thursday, July 30, 2020 9:19 PM

Answers

  • As was stated earlier, your gridview is data bound. You manually changing the control itself is stomping over the data that is bound. This isn't going to work. However at this point the question is completely in the ASP.NET realm which we do not provide support for here. If you want to continue down this path of trying to muck with your data bindings to get GridView to work then please post your question over in the ASP.NET forums.

    The original question of how to convert from int to string I believe has been answered because it was really just a C# question. Ultimately if you just use the real data instead of trying to manipulate the underlying controls this would all work. Perhaps the folks in the ASP.NET forums can explain better how GridView works and why you're having issues.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by wgraulich Wednesday, August 5, 2020 2:45 PM
    Wednesday, August 5, 2020 2:08 PM

All replies

  • Set a breakpoint on the first line, when hit step through the code.

    How to debug https://docs.microsoft.com/en-us/visualstudio/debugger/?view=vs-2019


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, July 30, 2020 9:40 PM
  • Please note that questions related to ASP.NET should be posted in the ASP.NET forums

    But your question seems to just be how to convert a string to an int. To do that use Int32.TryParse to attempt the conversion.

    if (Int32.TryParse(type.Text, out var value))
       //value has the integral value
    else
       //value is 0 because the text could not be converted
    But this is often overkill. You are binding to a data grid which means you probably pulled this data from your database. When you did that you got a datarow (or equivalent) and that is what is causing the rows to show up in the UI. Therefore when you are in the middle of data binding you don't need to parse controls because you still have access to that data. In your specific case during data binding you get the event args that has the `Row` property that is of type GridViewRow. That has the DataItem property which contains the original data that is being used to build the row. Therefore if you used some field in your dataset called `Id` to populate the `type` control then you can reference the (already typed) same field within this particular call. 


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, July 30, 2020 9:49 PM
  • Hi wgraulich,

    Thank you for posting here.

    I did a test with your code, and this code works well.

    I want to know how you assign initial values to these labels? When your program enters this code, there is no value that meets these conditions.

    Add a breakpoint under

    Label type = (Label)e.Row.FindControl("Jurisdiction")

    See what its value is.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, July 31, 2020 7:46 AM
  • Just the opposite.  I am trying to convert an int to string.
    Tuesday, August 4, 2020 11:51 AM
  • Just the opposite.  I am trying to convert an int to string.

    Why not use a reference table e.g.

    Then once loaded you have the text.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, August 4, 2020 12:45 PM
  • Maybe I didn't clarify what I was trying to say. My point was that you don't need to do a conversion against UI controls as you already have the underlying data. Just use the underlying data and you don't need conversion. Example given your specific code.

    //Assumption Jurisdiction control is backed by JurisdictionId
    //Your data is stored in a Datatable
    var data = e.Row.DataTime as DataRow;
    var id = data.Field<int>("JurisdictionId");
    var value = "";
    switch (id)
    {
       case 48: value = "Test2"; break;
       case 65: value = "Test3"; break;
       ...
    };
    type.Text = value;

    However looking closer at your variables you're actually going to mess up your data. Assuming you used data binding then your Jurisdiction label is bound to some JurisdictionId value (a number). But during the data binding event you're going to stomp over that with text. That means you just messed up the data binding that the GridView gave you. This is generally wrong.

    The better approach is to update your data to include the calculated property or at least use a calculated column in the GridView. Leave the original data bound column alone and hide it if you don't want it shown. The reason this is generally important is that if you're showing, for example, a series of jurisdictions (one per line) and if you stomp on the ID you won't know which row you're using. Using a calculated column is the better approach. Furthermore you can do this calculation back in your data object instead of in the UI removing the need for this event altogether.

    As Karen mentioned you should probably use a lookup table or store the text as part of your data if it is large. But if it is simple then a calculated property is fine. Example:

    public class MyData
    {
       //Use this property in GV to give access to ID, hide the column
       public int JurisdictionId { get; set; }
    
       //Use this property in GV as a textual description of the ID instead of the actual ID
       public string JurisdictionDescription 
       {
           switch (JurisdictionId)
           {
              case 1: return "First"; 
              ...
           };
    
           return "Unknown";
       }
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, August 4, 2020 2:07 PM
  • Hi

     <ItemTemplate>
        <asp:Label ID="Jurisdiction" runat="server" Text='<%#Eval("Model")%>' ></asp:Label>
    </ItemTemplate>
    
    If your Itemtemplate as asp Lable then you can use like you defined
      Label type = (Label)e.Row.FindControl("Jurisdiction");
      or
     Label type = (e.Row.FindControl("Jurisdiction") as Label);
    
    if your gridview bind by data table then you van access like
    
    
    var txt = e.Row.Cells[3].Text;
    
    
    

    Thanks and regards

    Tuesday, August 4, 2020 2:16 PM
  • Ok, so I converted the column to template:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." GridLines="Vertical" Font-Size="Larger" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                        <AlternatingRowStyle BackColor="#DCDCDC" />
                        <Columns>
                            <asp:BoundField DataField="Emp_Name" HeaderText="Employee Name" SortExpression="Emp_Name" />
                            <asp:BoundField DataField="Emp_ID" HeaderText="CAD ID #" SortExpression="Emp_ID" />
                            <asp:TemplateField HeaderText="Jurisdiction" SortExpression="JurisdictionID">
                                <ItemTemplate>
                                    <asp:Label ID="Jurisdiction" runat="server" Text='<%# Eval("JurisdictionID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="Pager" HeaderText="Cellphone #" SortExpression="Pager" />

    and I modified my cs code

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
    
                    Label type = (Label)e.Row.FindControl("Jurisdiction"); if (type.Text == "99")
                    {
    
                        type.Text = "Dispatch";
                    }
    
                    else if (type.Text == "48")
                    {
    
                        type.Text = "Law";
                    }
    
                    else if (type.Text == "65")
                    {
    
                        type.Text = "Fire";
                    }
    
                }
    
    
    
            }
        }
    }

    Still not working.   What am I missing.

    I also tried this cs code seeing how the JurisdictionID is the 3rd column in my gridview, and it doesn't work as well.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if (e.Row.Cells[3].Text == "99")
                        e.Row.Cells[3].Text = "Dispatch";
                    else if (e.Row.Cells[1].Text == "48")
                        e.Row.Cells[3].Text = "Law";
                    else if (e.Row.Cells[3].Text == "65")
                        e.Row.Cells[3].Text = "Fire";
                }
            }
        }
     }




    • Edited by wgraulich Wednesday, August 5, 2020 12:55 PM
    Wednesday, August 5, 2020 12:26 PM
  • As was stated earlier, your gridview is data bound. You manually changing the control itself is stomping over the data that is bound. This isn't going to work. However at this point the question is completely in the ASP.NET realm which we do not provide support for here. If you want to continue down this path of trying to muck with your data bindings to get GridView to work then please post your question over in the ASP.NET forums.

    The original question of how to convert from int to string I believe has been answered because it was really just a C# question. Ultimately if you just use the real data instead of trying to manipulate the underlying controls this would all work. Perhaps the folks in the ASP.NET forums can explain better how GridView works and why you're having issues.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by wgraulich Wednesday, August 5, 2020 2:45 PM
    Wednesday, August 5, 2020 2:08 PM