我有一个带有Sql连接的数据表,并且我正在尝试将其绑定到GridView,但是我收到的错误是找不到TypeName属性中指定的类型。 我的数据表代码如下所示:
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "TestConnectionString";
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "SELECT* FROM TestTable";
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
GridView1.DataSource = data;
}
和.aspx中的代码:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" >
<Columns>
<asp:BoundField DataField="Column1" HeaderText="Column1" ReadOnly="True" SortExpression="Column1" >
<HeaderStyle Width="450px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Column2" HeaderText="Column2" ReadOnly="True" SortExpression="Column2" >
<ItemStyle Width="400px" HorizontalAlign="Center" />
</asp:BoundField>
</Column>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="DataTable" TypeName="data"></asp:ObjectDataSource>
关于我做错了什么的建议?
答案 0 :(得分:1)
这不是ObjectDataSource
控件的使用方式。
如果您只想在第一页加载时绑定网格,则删除ObjectDataSource
控件,删除ObjectDataSource1_Selecting
事件处理程序,从{{1}中删除DataSourceID
属性只需在页面加载时绑定网格:
GridView
如果您想使用protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
using (SqlConnection conn = new SqlConnection("your connection string here"))
using (SqlCommand command = new SqlCommand("SELECT * FROM TestTable", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
}
控件,请为其指定有效的ObjectDataSource
和TypeName
,删除SelectMethod
事件处理程序,并拥有ObjectDataSource1_Selecting
返回数据:
SelectMethod
标记:
public static class YourDataSource
{
public static DataTable LoadSomeData()
{
using (SqlConnection conn = new SqlConnection("your connection string here"))
using (SqlCommand command = new SqlCommand("SELECT * FROM TestTable", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
return data;
}
}
}
如果你正在使用.NET 4.5,你也可以使用&#34;模型绑定&#34;在不使用数据源控件的情况下从代码隐藏加载数据:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="YourDataSource"
SelectMethod="LoadSomeData"
/>
标记:
public DataTable LoadSomeData()
{
using (SqlConnection conn = new SqlConnection("your connection string here"))
using (SqlCommand command = new SqlCommand("SELECT * FROM TestTable", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
return data;
}
}