Tuesday 16 December 2014

Adding multiple colors to single cell content using j script in asp.net

Here i bind data to GridView from database
Default.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Customer">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblCustomer" Text='<%# Eval("Customer") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactName">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblContactName" Text='<%# Eval("ContactName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactTitle">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblContactTitle" Text='<%# Eval("ContactTitle") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Code in Default.aspx.cs
SqlConnection con = new SqlConnection("Data Source=INHYDSPARSHIMON\\SQL2012;Initial Catalog=SMPL;User ID=sa;Password=******");
            SqlDataAdapter da = new SqlDataAdapter("Select Customer,ContactName,ContactTitle from tbl_Customer", con);
            DataSet ds = new DataSet();
            da.Fill(ds, "tbl");
            GridView1.DataSource = ds;
            GridView1.DataBind();

//Call javascript function in code behind
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "getdata();", true); 

Sample.js
function getdata() {
    var obj = document.getElementById('GridView1_lblContactName_0').innerText;
    var slp = [];
    slp = obj.split(' ');
    slp[0].fontcolor("green");
    for (var i = 0; i < slp.length; i++) {
        document.getElementById('GridView1_lblContactName_0').innerHTML = slp[0].fontcolor("green");
        document.getElementById('GridView1_lblContactName_0').innerHTML += slp[1].fontcolor("red");
    }
}
Output