Asp.net - GridView和DetailsView之间的绑定不起作用

时间:2015-06-28 07:42:32

标签: c# asp.net gridview detailsview

我创建了一个GridView和Contacs的DetailsView。我希望如果用户在GridView中选择一个联系人,它将在GridView中显示完整的详细信息。

这是aspx源代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Contacs.aspx.cs" Inherits="Atid4.Contacs" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                    DataKeyNames="ID" 
                    DataSourceID="SqlDataSourceMain" 
                    ShowSelectButton="true" 
                    EnableViewState="true"
                    EnablePersistedSelection="true" 
                    OnSelectedIndexChanged="GridViewMain_SelectedIndexChanged">
                    <Columns>
                        <asp:CommandField ShowSelectButton="True" />
                        <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
                        <asp:BoundField DataField="first_name" HeaderText="first_name" SortExpression="first_name" />
                        <asp:BoundField DataField="last_name" HeaderText="last_name" SortExpression="last_name" />
                    </Columns>
                </asp:GridView>

                <asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="SqlDataSourceMain" Height="50px" Width="125px">
                </asp:DetailsView>
                <asp:SqlDataSource ID="SqlDataSourceMain" runat="server" ConnectionString="<%$ ConnectionStrings:AtidConnectionString %>" SelectCommand="SELECT * FROM [Contacs]"></asp:SqlDataSource>

            </ContentTemplate>
        </asp:UpdatePanel>

    </div>
    </form>
</body>
</html>

我添加了一个函数GridViewMain_SelectedIndexChanged,当用户在Gridview中选择一行时调用该函数。当用户选择其中一个联系人时,会调用该函数,但联系人在GridView中不会更改。它继续显示第一个联系人。

这是背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Atid4
{
    public partial class Contacs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DetailsView1.DataBind();
            }
        }

        protected void GridViewMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsView1.SetPageIndex(GridView1.SelectedIndex);
        }
    }
}

感谢。

1 个答案:

答案 0 :(得分:1)

我在DetialsView中通过EnablePaging解决了它。