当我使用下面的代码时,我的gridview(ID = Gridview2)对象将使用经过硬编码的数据源完美地填充。我想使用动态生成的数据表(在调试数据表时,该数据表已成功地填充为行和列)。当我尝试将动态数据绑定到其他gridview对象(ID = Gridview1)并验证其具有数据源作为新创建的数据表时,屏幕上没有任何显示吗?
我在做什么错?我需要定义模板以使动态代码正常工作吗?
<asp:GridView ID="GridView2" runat="server" AllowSorting="True" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="true"
EmptyDataText="No results found" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
AllowSorting="True" AutoGenerateColumns="True">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
隐藏代码:
protected void btnSearch_Click(object sender, EventArgs e)
{
string domainToQueryFor = "domain";
string pinToQueryFor = "account";
DBConnectionlib.DBClass dbReader = new DBConnectionlib.DBClass();
dbReader.connectionInformation = @"Server=tcp:XXXXXXXXX,1433 ;Database=" + databaseName + ";Trusted_Connection=false;UID=" + databaseUserName + ";Pwd=" + databasePassword + "; ApplicationIntent=ReadWrite;Timeout=60;MultiSubnetFailover=True";
dbReader.tableName = tableName;
string currentSqlQuery = "select * from " + dbReader.tableName + " WHERE domain like '" + domainToQueryFor + "' and pin like '" + pinToQueryFor + "'";
dbReader.queryStatement = currentSqlQuery;
List<string> results = dbReader.readFromSqlDatabaseReturnList();
DataTable dt = createDataTable(results);
GridView1.DataSource = dt;
GridView1.DataBind();
}
答案 0 :(得分:1)
我必须添加它才能使其动态描绘
foreach (System.Data.DataColumn item in dt.Columns)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = item.ColumnName;
nameColumn.HeaderText = item.ColumnName;
GridView1.Columns.Add(nameColumn);
}
基本上没有明确声明/添加的列名,Gridview将不会显示。可能还可以使用<%bind%>命令在html代码中对它们进行硬编码,但是我希望它更具动态性,因此我以上述方式进行了操作。