Introduction For a long time, i was searching for the code, that enable me to dynamically change the background color and Alternating color of the DataGrid. But couldn't find anywhere on the net.
I was trying with my own ability to find the solution, luckily found.
BElow is the code, both the Server side and HTML code, Just cut and past it and it will run.
This code has been written in C#, however, it can be converted into VB.NET easily as the code is very basic.
Code
<script runat="server"> //page load event void Page_Load(Object Sender, EventArgs E) { if (IsPostBack==false) { DataGrid1.DataSource = CreateDataSource(); DataGrid1.DataBind(); } } //data source for the datagrid ICollection CreateDataSource() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime))); dt.Columns.Add(new DataColumn("BoolValue", typeof(bool))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); for (int i = 0; i < 9; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = DateTime.Now; dr[3] = (i % 2 != 0) ? true : false; dr[4] = 1.23 * (i+1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; } //will fire when the submit button will be clicked public void ChangeColor(Object Sender, EventArgs E) { try { DataGrid1.BackColor = ColorTranslator.FromHtml("#" + TextBox1.Text); DataGrid1.AlternatingItemStyle.BackColor = ColorTranslator.FromHtml("#" + TextBox2.Text); DataGrid1.DataBind(); //refresh the list DataGrid1.DataSource = CreateDataSource(); DataGrid1.DataBind(); } catch (Exception EE) { Label1.Text = "<font color='red'>Sorry, wrong color code, Please write HTML color code like (C0C0C0 for brown) " + EE.Source.ToString()+ " </font><br>"; } }
</script>
<!--HTML STARTS ---> <asp:Label id="Label1" runat="Server" enableviewstate="false"></asp:Label> <br /> Please write BackGround color for the Datagrid : <asp:TextBox id="TextBox1" runat="server" MaxLength="6"></asp:TextBox> <p> </p> <p> Please write Alternating BackGround color for the Datagrid : <asp:TextBox id="TextBox2" runat="server" MaxLength="6"></asp:TextBox> </p> <p> <asp:Button id="Button1" onclick="ChangeColor" runat="server" Text="Submit"></asp:Button> <br /> </p> <hr /> <p> <asp:DataGrid id="DataGrid1" runat="server"> <AlternatingItemStyle backcolor="#FFC0FF"></AlternatingItemStyle> </asp:DataGrid> </p> <!--CODE END --> <!-- Insert content here --> </form> <!--HTML ENDS --->
Thanks
Sheo
|
No responses found. Be the first to respond and make money from revenue sharing program.
|