TabContainer的OnActivetabChanged用法
在前台TabContainer添加事件
OnActivetabChanged="TabContainer1_ActiveTabChanged"
后台代码在OnActivetabChanged事件中执行GridView的绑定事件
protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e) { DataSet ds = new DataSet(); GridView1.DataSource = GetData(ds).Tables["Table_VIP"]; GridView1.DataBind(); }
注意,需要在Page_Load方法里调用该事件,否则在切换Tab的时候是没有反应的,因为它不会postback
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.TabContainer1_ActiveTabChanged(sender, e); } }
完整代码如下
前台
<%@ Page Title="主页" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AccessRemoteData._Default" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <%@ Register TagPrefix="UC1" TagName="Control1" Src="~/WebUserControl1.ascx" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" OnActivetabChanged="TabContainer1_ActiveTabChanged"> <asp:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel1"> <ContentTemplate> <UC1:Control1 ID="userControl1" runat="server" /> </ContentTemplate> </asp:TabPanel> <asp:TabPanel runat="server" HeaderText="TabPanel2" ID="TabPanel2"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </ContentTemplate> </asp:TabPanel> </asp:TabContainer> </asp:Content>
后台
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace AccessRemoteData { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.TabContainer1_ActiveTabChanged(sender, e); } } private DataSet GetData(DataSet ds) { string sqlConn = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString; SqlConnection conn = new SqlConnection(sqlConn); conn.Open(); string strSQL = "SELECT * FROM Table_VIP"; SqlDataAdapter adpt = new SqlDataAdapter(strSQL, conn); adpt.Fill(ds, "Table_VIP"); return ds; } protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e) { DataSet ds = new DataSet(); GridView1.DataSource = GetData(ds).Tables["Table_VIP"]; GridView1.DataBind(); } } }