Kurser och utbildning av IT-proffs och systemutvecklare

i Sök

Cornerstones utvecklarblogg

Alla Taggar

All Tags » ASP.Net 2.0   (RSS)
Sorry, but there are no more tags available to filter with.

  • Mark a GridView row, and move it with the up and down key

    I have notice that some people would like to add a way of using the key (up & down) buttons to move and mark a row in a GridView control, so I decided to write a post how you can easy add that kind of functionality to a GridView.

    To add client-side script event to the row to handle the event onKeyDown (we can use onKeyUp or Press also if we would like) we hook up to the GridView’s RowDataBoundEvent to make access to the current row that will be data bound. We can use the GridViewRowEventArgs’s Row property to get access to the current row. By using the Attri butes collection of t he Row property we can easy add attributes to our GridView (In this case the <tr> element that the GridView will render for us). We need to add three attributes to the row, id (to unique identify the row on the client-side), onKeyDown (to see if we press t he down or up button, for moving the marker) and the onClick (to make sure we can select a row and start moving from the selected row). The following code will add the “id” attribute to the <tr> element and it will only have the value of a counter (only to make this example simple), it will also add the onKeyDown event and call the method SelectRow when a key is pressed, and to the last the onClick event to make sure to select a start row:

     

    private int _i = 0;

     

     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

     {

           if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal))

           {

                e.Row.Attributes.Add("id", _i.ToString());

                e.Row.Attributes.Add("onKeyDown", "SelectRow();");

                e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString() + ");");

           

                _i++;

           }

     }

     

    The code above will make sure the GridView will render something similar to (at runtime):

     

    <table cellspacing="0" rules="all" border="1" id="GridView1" style="border-collapse:collapse;">

        <tr>

           <th scope="col">CategoryID</th><th scope="col">Name</th>

        </tr>

       <tr id="0" onKeyDown="SelectRow();" onClick="MarkRow(0);">

           <td>1</td><td>.Net 1.1</td>

       </tr>

       <tr id="1" onKeyDown="SelectRow();" onClick="MarkRow(1);">

           <td>2</td><td>.Net Framework 2.0</td>

        </tr><tr id="2" onKeyDown="SelectRow();" onClick="MarkRow(2);">

           <td>3</td><td>ADO.Net 2.0</td>

        </tr>

    </table>

     

    As you can see in the code above, the attribute id, onKeyDown and onClick is added to the <tr> element.  The onClick event will call the MarkRow method and pass the current row as an argument to make sure the row we click on will be marked and used as a start row.

     

    Now when we have done this, we need to add the client-side code that should handle the movement of the marker etc.  We can start with the MarkRow method that will be used to mark a row (change its background color):

     

    var currentRowId = 0;

     

    function MarkRow(rowId)

     {

            if (document.getElementById(rowId) == null)

                   return;

               

             if (document.getElementById(currentRowId) != null )

                    document.getElementById(currentRowId).style.backgroundColor = '#ffffff';

     

             currentRowId = rowId;

             document.getElementById(rowId).style.backgroundColor = '#ff0000';

     }

     

    The MarkRow will make sure a row will be marked and that a previous marked row will be remarked. The MarkRow takes one argument, rowId, which have the value of the row id to mark. The MarkRow will not do anything if the element with the specified rowId can’t be found (this will happen if we try to move out from the GridView when moving the marker with the up or down key).  The curretnRowId which is a global variable will be set to the current marked row, to keep track on which row that is selected. To remark a previous selected row we use the doecument.getElementById method to get the <tr> element with the currentRowId and see if it’s not null. If it’s not null a row is already selected and we need to clear its background color (The background color of the row is used to show what row is marked). After we have cleared a selected row, we set the currentRowId to the rowId that is passed as an argument to the MarkRow method. After this is done we set the background color of the selected row to a background color used to display that the row is marked.

     

    The MarkRow will be called when the onClick event is fired and it will make sure to set the currentRowId to the row that we have clicked on to be the start row (from where we can move the marker with the up and down key). It will also be called when we press the key up or down button to mark a new row. The method that handles the up and down keys is the SelectRow:

     

    function SelectRow()

    {

        if (event.keyCode == 40)

             MarkRow(currentRowId+1);

        else if (event.keyCode == 38)

              MarkRow(currentRowId-1);

     }

     

    The SeletRow method will check if the down key is pressed (keyCode = 40) or if the up key is pressed (keyCode = 38). Note: I’m so bad of naming methods so have that in mind, but I use the name SelectRow because when a key is pressed a row should be selected ;)

     

    When the down key is pressed, the MarkRow method will be called with the currentRowId as an argument. The currentRowId has the value of the id (which is the value of the “counter” that can also represents the index of a row) and add 1 to the id, so if we start or movement from row with id 1, we will move to row with the id 2. If we press the up key, we will decrease 1 from the current row, so if we start to move up from row with id 2, we will move to row with the id 1.

    Here is the whole code:

     

    Default.aspx.cs

     

    public partial class _Default : System.Web.UI.Page

    {

        private int _i = 0;

     

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal))

            {

                e.Row.Attributes.Add("id", _i.ToString());

                e.Row.Attributes.Add("onKeyDown", "SelectRow();");

                e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString() + ");");

           

                _i++;

            }

        }

    }

     

    Default.aspx

     

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

     

    <%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>

     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

     

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

        <title>Untitled Page</title>

        <script type="text/javascript">

     

            var currentRowId = 0;       

     

            function SelectRow()

            {

                if (event.keyCode == 40)

                    MarkRow(currentRowId+1);

                else if (event.keyCode == 38)

                    MarkRow(currentRowId-1);

            }

           

            function MarkRow(rowId)

            {

                if (document.getElementById(rowId) == null)

                    return;

               

                if (document.getElementById(currentRowId) != null )

                    document.getElementById(currentRowId).style.backgroundColor = '#ffffff';

     

                currentRowId = rowId;

                document.getElementById(rowId).style.backgroundColor = '#ff0000';

            }

       

        </script>

    </head>

    <body>

        <form id="form1" runat="server">

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"

                DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">

                <Columns>

                    <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False"

                        ReadOnly="True" SortExpression="CategoryID" />

                    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

                </Columns>

            </asp:GridView>

            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyBlogConnectionString %>"

                SelectCommand="SELECT [CategoryID], [Name] FROM [Categories]"></asp:SqlDataSource>

     

        </form>

    </body>

    </html>

     

    Note: This example uses a my blog database, so you can’t simply copy the whole code and think it will run, the code is only for demonstration purpose.

     



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • My Ajax presentation and some other information

    If you live in Sweden and close to Gothenburg and want to learn more about ASP.Net Ajax, in that case join the SweNug meeting (Sweden .Net User group) in the middle of April, I will be the speaker and it’s free! If you need more info please send me an e-mail. A colleague of mine (Mathias Olausson) are going to talk about VSTS on SweNug the 29th of Marsh, the target audience is developers (if I’m not wrong) and is also free, is that cool ;)

    To give you rest something, I’m going to give an example how to use the upcoming LinkDataSource control that will be shipped with “Orcas” later this year:

    <asp:LinkDataSource dataContext="MyContext" tablename="MyTableaName" filter="where myfield > 20" ...>

    The LinkDataSource control will automatically support update, delete, paging etc and by using the filter property we can define our query against our data context and table.

    The Workspace where I have added my WebPart components and Permission Manager will soon be closed down (the whole GotDotNet Workspaced will soon be gone), so the code will not be available to be downloaded. I could add it to CodePlex, but the time to maintain it etc, I don’t have. But there will be a solution for changing chromes for WebPart in an easier way in the next release of ASP.Net.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Keep the scroll position of a DIV after postback

    Maybe this Tips & Trix will be useful to some of you; at least I have seen that kind of question a lot of times. It’s about how to remain scroll positions in a <DIV> after a postback. The following will show you an example of how to do it; I use two client-side methods, one to save the scroll top position of the DIV, and one to restore it. I use a server-side <input> element to make sure to its value will be saved in the ViewState during postbacks (in that way I can keep the state of the scroll position of the DIV):

     

    <body onload="setScrollPos('myDiv')">

     

        <form id="form1" runat="server">

     

            <div id="myDiv" onscroll="saveScrollPos(this);" style="height:50px; width:100%; overflow:auto;">

                 ...

            </div>

     

            <asp:Button runat="server" ID="Button1" Text="Press Me!" />

     

            <input type="hidden" id="scrollPos" name="scrollPos" value="0" runat="server"/>

     

        </form>

       

        <script type="text/javascript" language="javascript">

       

            function saveScrollPos(object)

            {

                document.getElementById('scrollPos').value = object.scrollTop;

            }

     

            function setScrollPos(elementId)

            {

                document.getElementById(elementId).scrollTop = document.getElementById('scrollPos').value;

            }

           

        </script>

     

    </body>

     

     



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Send an e-mail with the content of a GridView

    I have seen several questions lately on the ASP.Net Forum about how to expert and send an e-mail with the content of a GridView in ASP.Net 2.0. So I decided to post a short post about how you can make it possible.

     

    To get the content (HTML format) from a control you can use the control’s RenderControl method. This method takes an HtmlTextWriter as an argument. The following example shows how you can simply get the content from a GridView control:

     

    StringWriter stringWriterTmp = new StringWriter();

           

    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriterTmp);

    GridView1.RenderControl(htmlWriter);

     

    string htmlContent = stringWriterTmp.ToString();

     

    When you use the HtmlTextWriter you need to pass a TextWriter as an argument to the constructor. This is done by using the StringWriter class (the StringWriter inherits the TextWriter class). The RenderControl method of the GridView control will write down the control’s content to the HtmlTextWriter you pass as an argument, and you can then use the StringWriter to get the HTML content.

     

    If you add the code above for a Click event of a button control, you will get an exception about the GridView need to be placed inside of a FORM element (HtmlForm) with the runat=”server” attributes set or something similar. This is because the Page’s VerifyRenderingInServerForm method will be called to verify if the control is rendered inside of the FORM element. In this case you render it manually and it will be handling outside of a FORM, and that is the reason why you get the exception. To handle it, you can for example create our own custom Page and override the VerifyRenderingInServerForm method and make sure it will not perform the verification of your GridView control. You also need to inherit our custom Page. Here is an example:

     

    public partial class Default : MyPage

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }

     

        protected void Button1_Click(object sender, EventArgs e)

        {

              StringWriter stringWriterTmp = new StringWriter();

            

              HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriterTmp);

              GridView1.RenderControl(htmlWriter);

     

              string htmlContent = stringWriterTmp.ToString();

     

              ...

     

        }

    }

     

     

    public class MyPage : Page

    {

        public override void VerifyRenderingInServerForm(Control control)

        {

            GridView grid = control as GridView;

     

            if (grid != null && grid.ID == "GridView1")

                return;

            else

                base.VerifyRenderingInServerForm(control);

        }

    }

     

    Note: GridView1 in the code above is the ID set to the GridView’s ID attribute in the default.aspx page.

     

    As long as there are no controls in the GridView that can do a postback, the code above will work fine. But if you have controls that do a postback, like columns with sorting or paging enable etc. You will get an exception that the controls aren’t rendered inside of an HtmlForm.

     

    To solve that issue, you can for example hide all controls that do a postback, or create a new instance of the HtmlForm and add it to a new instance of the Page object. Here is an example where the custom Page is used to by pass the call to the VerifyRenderingInServerForm if the control is a GridView with a specific id:

     

    protected void Button1_Click(object sender, EventArgs e)

    {

       MyPage tmpPage = new MyPage();

       HtmlForm form = new HtmlForm();

     

       form.Controls.Add(GridView1);

       tmpPage.Controls.Add(form);

           

       StringWriter sw = new StringWriter();

           

       HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);

       form.Controls[0].RenderControl(htmlWriter);

     

       string htmlContent = sw.ToString();

    }

     

    The problem with this solution is that the GridView will not be rendered to the “main” page. To solve that you can for example first get the position of where the GridView is added to the main page (can use the HtmlForm’s IndexOf property), and then call the RenderControl method, and after that add the GridView to the main Page HtmlForm at the same position by using the AddAt method of the HtmlForm’s Controls property. But this can mess up the ViewState so be careful if you use that solution. Another solution would be to dynamically create and add a new copy of your GridView to the new instance of the Page object. If you don’t want to dynamically create new GridView, you can for example when you have sent the e-mail use Response.Redirect to redirect back the page and show it from its original state. You can of course also redirect to another page that show a message that the mail have been sent etc. There are several solutions to solve it, but at least, now you know how to get the content out from the GridView.

     

    To send the content through an e-mail we can use the SmtpClient class, here is an example:

     

    using (MailMessage mailMessage = new MailMessage(from, sendTo))

    {

       mailMessage.Subject = “My Exported GridView”;

       mailMessage.Body = htmlContent;

       mailMessage.IsBodyHtml = true;

     

       SmtpClient smtpClient = new SmtpClient(myHost);

       smtpClient.Send(mailMessage);

    }

     

    I should not use the RenderControl at all if I need to send the content through an e-mail or export it to other files. Instead I should create a business object that would get the data from the data source and export it to my own defined XML format, and use XSLT to transform the XML into a HTML or other formats.

    Computers Blogs - Blog Top SitesBloggtoppen.se


    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Microsoft ASP.NET Futures

    You can now download the May release o the ASP.Net Futures. ASP.Net Futures will work for both VS 2005 and VS “Orcas”. With the ASP.Net Futures new controls, here is a list of some of them:

    DynamicRssLink

    The DynamicRssLink control will display a RSS link for you. It will use the name of the folder and use the name to get information out from a table with the same name (by default).

    <asp:DynamicRssLink ID="DynamicRssLink1" runat="server"/>

    When you put the DynamicRssLink to the page you need to specify a connection string, this could be done by using the <dynamicDataControls> section in the web.config file:

    <dynamicDataControls connectionString="MyBlogConnectionString" showAllTables="false">
         <nameMap>
               <add table="Posts" pathPrefix="~/MyPosts"/>
         </nameMap>
    </dynamicDataControls>

    By using the <nameMap> section, you can map a path to a specific table. The example above will make sure a page under the MyPosts that has the DynamicRssLink, will generate RSS from the specified table, in this case the Posts table. If you use for example IE 7.0 and press on the RSS link that will be rendered by the DynamicRssLink, you will see the rows added to the mapped table. If you press on a post, you will be navigated to details.aspx page in the same folder where the page with the control is located.

    DynamicDetails

    The DynamicDetails will render a details view control for you with intert, edit and update capability.

    <asp:DynamicDetails ID="DynamicDetails1" runat="server" />

    It will work in a similar way as the DynamicRssLink control when it gets the data from a data source; it will get the table with the same name as the folder where the page with the control is located and show the content in a DetailsView control.

    Note: The DynamicDetails will inherit the DetailsViewExtenderBase class, that in turn inherit the CompositeDataBoundControlExtender<DetailsView>.

    We can also here use the <nameMap> element of the <dynamicDataControls> section in web.config, to map our folder to a specific table if the name of the folder will not be the same as a table in our specified data source.

    DynamicList

    The DynamicList control will work in a similar way as the DynamicDetails control but will instead render an extended GridView control.

    <asp:DynamicList ID="DynamicList1" runat="server" />

    DynamicNavigator

    The DynamicNavigator will extend the Menu control.

    DynamicFilter

    The DynamicFilter control will extend the ListControl and you can use it for example to filter a DynamicList.

    DynamicInsert

    The DynamicInsert is similar to the DynamicDetails, but it will show t he DetailView in an Insert mode.

    DynamicAutoData

    The DynamicAutoData can be used to create a Master-Detail view page. When you add this control to a page, it will use the name of the file as the table it retrieves the data from as long as the file is not located in a folder that is mapped in the <nameMap> section. It will then render a DynamicRssLink, DynamicFilter, DynamicList, DynamicDetails and a DynamicInsert control to the page. If you add the control to a page under folder that exists in the <nameMap>, it will only by default render a DynamicDetails control.

    SearchDataSource

    The SearchDataSource contol is a new kind of data source control that can be used together with a data-bound control. The control can be used to search for content and display in the data-bound control that uses it as a source. You can for example do a Microsoft Live Search from your app, and display the search result in a GridView control etc. You can in web.config change provider for the SearchDataSource. Out from the box we have a provider for Microsoft Live Search.

    History

    The History control will handle the Back button problem when you are doing an async. Postback with ASP.Net Ajax. It will use a IFRAME to handle the history.

    This was a short description of some of the controls shipped with the current version of ASP.Net Futures.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • How to simply modify a GridView

    There are still several of people who posts questions about changing the GridView dynamically. I will in this post explain some basics about how to change the GirdView.

     

    When you bind data to a GridView, you can get access to the current row that is data bound by using the RowDataBound event:

     

    VB.Net:

     

    Protected Overridable Sub OnRowDataBound(ByVal e As GridViewRowEventArgs)

     

    C#:

     

    protected virtual void OnRowDataBound(GridViewRowEventArgs e);

     

    The RowDataBound event will be trigged if the Header, rows, Pager and Footer etc is rendered.

     

    The RowDataBound event takes two arguments, the “source” which is the instance of the GridView control, and the “e” which is of type GridViewRowEventArgs. The GridViewRowEventsArgs gives us all the information you need to get access to a row. By using the Row property of the GridViewRowEventsArgs you will get access to the current row that is data bound. The Row is of type GridViewRow. Let’s take a look at two basic properties of the GridViewRow that you will probably use often when you want to modify the GridView.

     

    RowType, return the type of the row, for example if it’s a Header or normal row etc.

    RowState, return the state of the row, for example if the row is in edit state, normal state or a selected state etc.

     

    The RowType is a DataControlRowType enum. The value of the enum is the following:

     

    DataRow

    EmptyDataRow

    Footer,

    Header

    Pager

    Seperator

     

    The GridViewRow will have the RowType DataRow if the row that is currently data bound is a normal row. A normal row is a row that displays the data from the data source. If you bind empty data to the GridView and use the EmptyDataTemplate, the GridViewRow will have its type set to EmptyDataRow. If the row is a header or footer, it will have the state Header or Footer. If we have enable Paging and the GridView reach the row that represents the pager, it will have the type Pager. The following code will check if the current row is a Header row:

     

    VB.Net:

     

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

     

            If e.Row.RowType = DataControlRowType.Header Then

     

            End If

     

    End Sub

     

    C#:

     

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

         if (e.Row.RowType == DataControlRowType.Header)

         {

         }

     }

     

    The code you put inside the body of the “if” block will only be called when the row is the header of the GridView. If you are only interested in the row that should display the data you bind to the GirdView, you can instead check if the type is a DataRow:

     

    VB.Net:

     

    If e.Row.RowType = DataControlRowType.DataRow Then

     

    End If

     

    C#:

     

    if (e.Row.RowType == DataControlRowType.DataRow)

    {

    }

     

    If you need to know what state a row is in, you can use the RowState property of the GridViewRow. The RowState can be the following:

     

    Alternate

    Edit

    Insert

    Normal

    Selected

     

    If you have selected a row, the state of the row will be Selected. If the row is a normal row (not selected, not in edit mode etc) the state is Normal. If you have marked a row for edit, the state is Edit. Every other row in the GridView has the state set to Alternate. The following figure shows both the RowType and the RowState values of a GridView:

     

     

    If you want to get access to the columns for the current row that is data bound, you can use the Cells property of the GridViewRow:

     

    e.Row.Cells

     

    The Cells collection is zero based and has a list of TableCell objects, so to get the second column in a GridView, you use the index 1:

     

    VB.Net:

     

    e.Row.Cells(1)

     

    C#

     

    e.Row.Cells[1]

     

    If you only use a BoundField in your GridView:

     

    <asp:GridView ID="GridView1" …>

        <Columns>

            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" .../>

            <asp:BoundField DataField="CompanyName" HeaderText="CustomerID" .../>

            ...     

        </Columns>

    </asp:GridView>

     

    You can use the Text property of the TableCell to get access to the value of a specified column, or also change the value:

     

    VB.Net:

     

    Dim customerId As String = e.Row.Cells(0).Text

     

    e.Row.Cells(0).Text = “New value for the first column”

     

    C#

     

    String customerId = e.Row.Cells[0].Text;

     

    e.Row.Cells[0].Text = “New value for the first column”;

     

    The TableCell object also has style properties etc, so you can easy change the style of a table cell. For example maybe you want to set the background color of a cell to be a specific color based on the cells value. The following is an example how you can do that, it will check if the second column has the value ANTON, if it has, the columns background color will be set to red:

     

    VB.Net:

     

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

     

            If e.Row.RowType = DataControlRowType.DataRow Then

     

                If e.Row.Cells(1).Text = "ANTON" Then

                    e.Row.Cells(1).Style.Add("background-color", "red")

     

                End If

     

            End If

     

    End Sub

     

    C#

     

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

         if (e.Row.RowType == DataControlRowType.DataRow)

         {

                if (e.Row.Cells[1].Text == “ANTON”)

                {

                       e.Row.Cells[1].Style.Add(“background-color”,”red”);

                 }

         }

    }

     

    It can sometimes be stupid to use the Text property and get the value in a cell because the value can be changed if we format values etc. So another way (which I think is better) is to get access to the “raw” object that is bind to the current view. This can be done by using the DataItem property of the GridViewRow object:

     

    e.Row.DataItem

     

    If you have bound a collection of your own objects to the GridView, for example a list of Customer, you can cast the DataItem to Customer to get access to the Customer interface and its values:

     

    VB.Net:

     

    Dim customer As Customer = DirectCast(e.Row.DataItem, Customer)

     

    C#

     

    Customer customer = (Customer)e.Row.DataItem;

     

    So instead of using the Text property of the TableCell to see if a column has a specific value, you can now use the DataItem to get the “raw” data:

     

    VB.Net:

     

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

     

            If e.Row.RowType = DataControlRowType.DataRow Then

     

                Dim customer As Customer = DirectCast(e.Row.DataItem, Customer)

     

                If customer.ID = "ANTON" Then

                    e.Row.Cells(1).Style.Add("background-color", "red")

                End If

     

            End If

     

    End Sub

     

    C#

     

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

         if (e.Row.RowType == DataControlRowType.DataRow)

         {

                Customer customer = (Customer)e.Row.DataItem;

     

                if (customer.ID == “ANTON”)

                {

                       e.Row.Cells[1].Style.Add(“background-color”,”red”);

                 }

         }

    }

     

    If you don’t use a BoundField and instead use a TemplateField and want to modify the controls inside of the template, you can use the FindControl method of the TableCell to find a control located inside of your template. For example:

     

    <asp:GridView ID="GridView1" ...>

      <Columns>

        <asp:BoundField DataField="CustomerID" ... />

         <asp:TemplateField HeaderText="CompanyName" ...>

           <ItemTemplate>

             <asp:Label ID="Label1" runat="server" Text='<%# Bind("CompanyName") %>'/>

           </ItemTemplate>

         </asp:TemplateField>

       </Columns>

    </asp:GridView>

     

    If you want to get the Label control from your second column in the GridView above you write something like this:

     

    VB.Net:

     

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

     

            If e.Row.RowType = DataControlRowType.DataRow Then

     

                    Dim myLabel As Label = DirectCast(e.Row.Cells(1).FindControl(“Label1”))

     

            End If

     

    End Sub

     

    C#

     

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

         if (e.Row.RowType == DataControlRowType.DataRow)

         {

       Label myLabel = (Label)e.Row.Cells[1].FindControl(“Label1”);

         }

    }

     

    You can also use the Controls property of the TabelCell to get a control if you know the index (position) of the control in the control collection.

     

    You can also use the GridViewRow’s FindControl to locate the control in a column. For example:

     

    VB.Net:

     

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

     

            If e.Row.RowType = DataControlRowType.DataRow Then

     

                    Dim myLabel As Label = DirectCast(e.Row..FindControl(“Label1”))

     

            End If

     

    End Sub

     

    C#

     

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

         if (e.Row.RowType == DataControlRowType.DataRow)

         {

    Label myLabel = (Label)e.Row.FindControl(“Label1”);

         }

    }

     

    Summary

     

    In this post you have seen how you can use the RowDataBound event to get access to different type of rows. You have also seen how you can get a value out from a column and also how easy it’s to customize a column, for example changing the background color based on a value. You have also seen how easy it’s to find a control if a TemplateField is used instead of a BoundField.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se

Den här bloggen

Syndication