我有一个ListView
控件,带有来自MS Access的数据源,现在我想从ListView中选择一个项目,数据将显示在TextBox等中。
如何在ListView中选择项目?
答案 0 :(得分:0)
你的问题有点令人困惑。您是否询问如何在选择列表项时调用方法?
谷歌搜索后应该有很多答案,但这是一个简单的例子:
带有OnSelectedIndexChanged的ASP.NET ListBox:
<asp:ListBox runat="server" ID="lbListBox" OnSelectedIndexChanged="lbListBox_OnIndexChanged"/>
ASP.NET TextBox:
<asp:TextBox runat="server" ID="tbTextBox"></asp:TextBox>
CodeBehind.cs中调用的方法:
protected void lbListBox_OnIndexChanged(object sender, EventArgs e)
{
var listBoxText = lbListBox.SelectedItem.ToString();
tbTextBox.Text = listBoxText;
}
答案 1 :(得分:-1)
尝试一下......请更改您的数据提供者名称和连接字符串属性
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="PId" OnSelectedIndexChanging="ListView1_SelectedIndexChanging">
<LayoutTemplate>
<table>
<tr>
<th>
Select
</th>
<th>
Product ID
</th>
<th>
Product Name
</th>
<th>
Unit Price
</th>
</tr>
<tbody>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="lnkSelect" Text="Select" CommandName="Select" runat="server" />
</td>
<td>
<%# Eval("ProductID")%>
</td>
<td>
<%# Eval("ProductName")%>
</td>
<td>
<%# Eval("UnitPrice")%>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr>
<td>
<asp:LinkButton ID="SelectLinkButton" Text="Select" CommandName="Select" runat="server"
ForeColor="White" />
</td>
<td>
<%# Eval("PId")%>
</td>
<td>
<%# Eval("PName")%>
</td>
<td>
<%# Eval("Price")%>
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
<br />
<asp:Label ID="MessageLabel" runat="server" Text="Label"></asp:Label>
</div>
</form>
//代码隐藏
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string constr = "Data Source=Your Server;Database=Your DB;uid=User Name; pwd=Your Password;";
string query = "SELECT PId, PName,Price FROM tblProducts";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
ListView1.DataSource = table;
ListView1.DataBind();
}
protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
ListView1.SelectedIndex = e.NewSelectedIndex;
string pid = ListView1.SelectedDataKey.Value.ToString();
MessageLabel.Text = "Selected Product ID: " + pid;
BindData();
}
}