当前位置: 代码迷 >> ASP.NET >> 提示异常:Both DataSource and DataSourceID are defined on 'GridView1'
  详细解决方案

提示异常:Both DataSource and DataSourceID are defined on 'GridView1'

热度:7208   发布时间:2013-02-25 00:00:00.0
提示错误:Both DataSource and DataSourceID are defined on 'GridView1'.
网上查了一下,GridView不能绑定2个数据,那我要实现代码所示功能,该如何解决?

<body>
  <form id="form1" runat="server">
  <div>
  请选择省份:<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" Width="112px">
  <asp:ListItem>请选择</asp:ListItem>
  <asp:ListItem>厦门</asp:ListItem>
  <asp:ListItem>北京</asp:ListItem>
  <asp:ListItem>上海</asp:ListItem>
  </asp:DropDownList>
  <asp:Button ID="Button1" runat="server" Text="提交" onclick="Button1_Click" />
  <p></p>
  </div>
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
  DataKeyNames="ID" DataSourceID="SqlDataSource1" EnableModelValidation="True">
  <Columns>
  <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
  ReadOnly="True" SortExpression="ID" />
  <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
  <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
  <asp:BoundField DataField="Address" HeaderText="Address" 
  SortExpression="Address" />
  <asp:BoundField DataField="TelePhone" HeaderText="TelePhone" 
  SortExpression="TelePhone" />
  <asp:BoundField DataField="Sex" HeaderText="Sex" SortExpression="Sex" />
  </Columns>
  </asp:GridView>
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  ConnectionString="<%$ ConnectionStrings:ProductConnectionString %>" 
  SelectCommand="SELECT * FROM [UserInfo]"></asp:SqlDataSource>
  </form>
</body>





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;

public partial class _Default : System.Web.UI.Page 
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void Button1_Click(object sender, EventArgs e)
  {
  string strConn = ConfigurationManager.ConnectionStrings["ProductConnectionString"].ConnectionString;
  SqlConnection conn = new SqlConnection(strConn);
  SqlCommand cmd = new SqlCommand(strConn, conn);
  SqlDataAdapter myda = new SqlDataAdapter();
  DataSet ds = new DataSet();
  try
  {
  conn.Open();
  cmd.Connection = conn;
  string Address = DropDownList1.SelectedItem.ToString();
  cmd.CommandText = "select ID,Name,Sex,Age,TelePhone from UserInfo where Address=@Address";
  myda.SelectCommand = cmd;

  //定义参数
  SqlParameter mypara = new SqlParameter();
  mypara.ParameterName = "@Address";
  相关解决方案