Merhaba arkadaşlar bu makalemizde OnRowDataBound a yazacağımız küçük bir kod parçasıyla; Fiyat sütunumuzunda ki fiyat değer aralığına göre arka plan rengini değiştireceğiz.
GridView in AutoGenerateColumns="false" yapın.
Screenshot
Şekil 1
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData();
}
}
protected void bindData()
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\kategori.mdf;Integrated Security=True");
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[Table]", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = e.Row.Cells[3];
int fiyat = int.Parse(cell.Text);
if (fiyat > 0 && fiyat <= 10)
{
cell.BackColor = Color.Green;
}
if (fiyat > 10 && fiyat <= 15)
{
cell.BackColor = Color.LightYellow;
}
if (fiyat > 15 && fiyat <= 50)
{
cell.BackColor = Color.Red;
}
}
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound" runat="server">
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width = "50"/>
<asp:BoundField DataField="yazar" HeaderText="Yazar" ItemStyle-Width = "200"/>
<asp:BoundField DataField="kitap" HeaderText="Kitap" ItemStyle-Width = "200"/>
<asp:BoundField DataField="fiyat" HeaderText="Fiyat" ItemStyle-Width = "50"/>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN
0 comments:
Yorum Gönder