Cheers,
У меня есть ASP веб-форма, которая загружает Gridview, «Gridview1», который в некоторых случаях показывается пользователям, а в других случаях скрыт. Gridview был создан в конструкторе, а Gridview.DataSourceID связан с SqlDataSource в файле aspx.
Теперь я пытаюсь добавить функцию поиска, которая использует два текстовых поля и событие нажатия кнопки для запроса данных из таблицы и перезагрузки Gridview1 с меньшим набором данных с использованием CodeBehind.
Есть тонны сообщений здесь на SO и других форумах об этой конкретной ошибке, но я думаю, что мне нужны и DataSource, определенный в CodeBehind, и DataSourceID, определенный для t ie в исходном SqlDataSource в файле aspx внешнего интерфейса.
Есть ли способ использовать оба определения? Я пытался обманом заставить CodeBehind отказаться от DataSourceID с помощью
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSourceID = null;
GridView1.DataSource = rdr;
GridView1.DataBind();
Но это просто вызвало другую ошибку. Есть ли способ определить оба? Или я могу привязать результаты SQL обратно к Gridview, используя GridView1.DataSourceID
вместо GridView1.DataSource
?
Вот страница ASP:
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeFile="Junk2.aspx.cs" Inherits="CPITraining.Junk2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>
.container {
max-width: 1530px;
}
.niceLabels {
margin:15px 0px 15px 0px;
display:inline-block;
font:normal 30px Arial;
}
</style>
<%-- TOP CONTAINER --%>
<div class="container" style="width:1500px">
<div class="row">
<div class="col-md-12">
<div style="background-color:#FFFFFF">
<%-- EMPLOYEE GridView1 Window --%>
<asp:Label ID="EmplList" runat="server" CssClass="niceLabels">Employee Listing</asp:Label>
<div>
<asp:TextBox ID="txtBadge" runat="server" OnInit="txtBadge_Init"></asp:TextBox>
<asp:TextBox ID="txtLast" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</div>
<asp:GridView ID="GridView1" DataKeyNames="badge_id" runat="server" BackColor="White" BorderColor="#999999"
BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
GridLines="Vertical" DataSourceID="SqlDataSource1" AllowPaging="True" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="BADGE_ID" HeaderText="BADGE_ID" SortExpression="BADGE_ID" />
<asp:BoundField DataField="FIRSTNAME" HeaderText="FIRSTNAME" SortExpression="FIRSTNAME" />
<asp:BoundField DataField="LASTNAME" HeaderText="LASTNAME" SortExpression="LASTNAME" />
<asp:BoundField DataField="TITLE" HeaderText="TITLE" SortExpression="TITLE" />
<asp:BoundField DataField="deptname" HeaderText="deptname" SortExpression="deptname" />
<asp:BoundField DataField="Column1" HeaderText="Column1" ReadOnly="True" SortExpression="Column1" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</div>
</div>
</div>
<%-- BOTTOM CONTAINER --%>
<div class="container">
<div class="row">
<div class="col-md-3">
<div style="background-color:#FFFFFF">
<%-- LEFT DETAILS VIEW --%>
<asp:Label ID="EmplHist" runat="server" CssClass="niceLabels">Employee History</asp:Label>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="badge_id"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="SqlDataSource2" ForeColor="Black" GridLines="Horizontal" Height="50px" Width="125px">
<EditRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:BoundField DataField="BADGE_ID" HeaderText="BADGE_ID" SortExpression="BADGE_ID" />
<asp:BoundField DataField="FIRSTNAME" HeaderText="FIRSTNAME" SortExpression="FIRSTNAME" />
<asp:BoundField DataField="LASTNAME" HeaderText="LASTNAME" SortExpression="LASTNAME" />
<asp:BoundField DataField="TITLE" HeaderText="TITLE" SortExpression="TITLE" />
<asp:BoundField DataField="deptname" HeaderText="deptname" SortExpression="deptname" />
<asp:BoundField DataField="Expr1" HeaderText="Expr1" ReadOnly="True" SortExpression="Expr1" />
</Fields>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
</asp:DetailsView>
</div>
</div>
<div class="col-md-9">
<div class="row" style="background-color:#FFFFFF">
<%-- PROCEDURE CLASSES VIEW --%>
<asp:Label ID="ProcTraining" runat="server" CssClass="niceLabels">Procedure Training Records</asp:Label>
<asp:GridView ID="GridView2" runat="server" DataKeyNames="badge_id"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource3" ForeColor="Black" GridLines="Vertical" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
<div class="row"> </div>
<div class="row" style="background-color:#FFFFFF">
<%-- NONPROCEDURE CLASSES VIEW --%>
<asp:Label ID="NonprocTraining" runat="server" CssClass="niceLabels">NonProcedure Training Records</asp:Label>
<asp:GridView ID="GridView3" runat="server" DataKeyNames="badge_id"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource4" ForeColor="Black" GridLines="Vertical" AllowPaging="True">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</div>
</div>
</div>
<p>
/// various <asp:SqlDataSources, etc...
</asp:Content>
А вот CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace CPITraining
{
public partial class Junk2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView1.SelectedRow != null)
{
//when DETAILS are up
DetailsView1.Visible = true;
GridView1.Visible = false;
EmplList.Visible = false;
EmplHist.Visible = true;
ProcTraining.Visible = true;
NonprocTraining.Visible = true;
}
else
{
//when MAIN list is up
DetailsView1.Visible = false;
GridView1.Visible = true;
EmplList.Visible = true;
EmplHist.Visible = false;
ProcTraining.Visible = false;
NonprocTraining.Visible = false;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
string TrainingDBConnection = ConfigurationManager.ConnectionStrings["TrainingDBConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(TrainingDBConnection))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
StringBuilder sbCommand = new StringBuilder("Select * from blah, blah, blah.... where 1 = 1");
if (txtBadge.Value.Trim != "")
{
sbCommand.Append(" AND BADGE_ID=@txtBadge");
SqlParameter param = new SqlParameter("@txtBadge", txtBadge.Value);
cmd.Parameters.Add(param);
}
if (txtLast.Value.Trim != "")
{
sbCommand.Append(" AND LASTNAME=@txtLast");
SqlParameter param = new SqlParameter("@txtLast", txtBadge.Value);
cmd.Parameters.Add(param);
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSourceID = null; // <--- this didn't work
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Спасибо за вашу помощь!