ListView da Veri Seçimi
Merhaba arkadaşlar bu makalemizde ListView nesnesine LinkButton ekleyeceğiz ve bu butona basıldığında listview nesnesinde satırı seçeceğiz. Seçili satır no’yu projeye ekleyeceğimiz Label de göstereceğiz.
Screenshot
Şekil 1
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
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 baglan = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\kategori.mdf;Integrated Security=True;Connect Timeout=30");
{
baglan.Open();
SqlCommand cmd = new SqlCommand("Select * From [Table] ", baglan);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
ListView1.DataSource = table;
ListView1.DataBind();
baglan.Close();
}
}
protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
ListView1.SelectedIndex = e.NewSelectedIndex;
string id = ListView1.SelectedDataKey.Value.ToString();
Label1.Text = "Seçili Kayıt No: " + id;
BindData();
}
}
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:ListView ID="ListView1" runat="server" DataKeyNames="Id" OnSelectedIndexChanging="ListView1_SelectedIndexChanging">
<LayoutTemplate>
<table style="border: solid 2px #336699;" cellspacing="0" cellpadding="3" rules="all">
<tr style="background-color: #336699; color: White;">
<th>Seç</th>
<th>Id</th>
<th>Yazar</th>
<th>Kitap</th>
<th>Fiyat</th>
</tr>
<tbody>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="lnkSelect" Text="Seç" CommandName="Select" runat="server" />
</td>
<td><%# Eval("Id")%></td>
<td><%# Eval("Yazar")%></td>
<td><%# Eval("Kitap")%></td>
<td><%# Eval("Fiyat")%></td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr style="background-color: #336699; color: White;">
<td>
<asp:LinkButton ID="lnkSelect" Text="Seç" CommandName="Select" runat="server"
ForeColor="White" />
</td>
<td><%# Eval("Id")%></td>
<td><%# Eval("Yazar")%></td>
<td><%# Eval("Kitap")%></td>
<td><%# Eval("Fiyat")%></td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN