新问题。 我有这个作为我的gridview,我想拥有它,所以当页面加载时,网格视图中充满了数据库信息。
以下是gridview的代码。以下是c#代码。
更新
<asp:GridView ID="RegistrantsView" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="True"
CellPadding="4"
ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
C#:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FFL-New DataConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
connection.Open();//opens connection on page load
SqlCommand selectAllCommand = new SqlCommand();
selectAllCommand.CommandText = "select * from registrants";
selectAllCommand.Connection = connection;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = selectAllCommand;
DataTable dt = new DataTable();
sda.Fill(dt);
RegistrantsView.DataSource = dt;
RegistrantsView.DataBind();
}
答案 0 :(得分:0)
首先,您应该注意,您的查询很容易SQL Injections这是安全风险 !!
而不是ExecuteNonQuery使用DataAdapter并填充DataTable,然后在DataBind
之前为RegistrantsView 设置DataSource:
protected void SearchButton_Click(object sender, EventArgs e)
{
string searchBoxValue = SearchBox.Text;
string columnNameValue = ColumnName.SelectedValue;
columnNameValue.ToLower();
string sqlQuery = "select * from registrants";
DataTable dt = new DataTable();
using (SqlCommand searchCommand = new SqlCommand(sqlQuery, connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
RegistrantsView.DataSource = dt;
RegistrantsView.DataBind();
}
如果它在PageLoad中:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
string sqlQuery = "select * from registrants";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FFL-New DataConnectionString"].ConnectionString))
{
using (SqlCommand searchCommand = new SqlCommand(sqlQuery, connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
}
RegistrantsView.DataSource = dt;
RegistrantsView.DataBind();
}
}