前端
1、添加控件GridView,添加数据源,接着按步骤选择自己的数据库 添加数据源显示数据有俩种方法: (1)一种方法是在GridView控件上直接按步骤添加数据源,及设计想要显示的列,这种方法比较直接简单 (2)另一种方法是直接用后端的代码实现显示数据 鉴于后边的功能想要把“编辑”和“删除”列加在后边,而通过代码显示的数据,新添加的列在前边,不美观,所以进行了手动添加数据源这步操作 - <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" PageSize="10" AllowPaging="True"
- ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
- OnRowUpdating="GridView1_RowUpdating"
- OnRowCancelingEdit="GridView1_RowCancelingEdit" onrowdatabound="GridView1_RowDataBound"
- >
- <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
- <PagerSettings Visible="False" />
- <Columns>
- <asp:BoundField DataField="UserID" HeaderText="用户" ReadOnly="True"
- SortExpression="UserID" />
- <asp:BoundField DataField="Context" HeaderText="感谢留言"
- SortExpression="Context" />
- <asp:CommandField ShowEditButton="True" />
- <asp:CommandField ShowDeleteButton="True" />
- </Columns>
- <RowStyle ForeColor="#000066" />
- <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
- <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
- </asp:GridView>
复制代码
后端
1、连接数据库 - private DataSet GetData()
- {
- //连接数据库
- // 数据库连接,用的是相对路径 数据库文件名:Database.mdb存放于 文件夹app_data 中
- OleDbConnection conn = new OleDbConnection();
- conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/app_data/Database.mdb");
- OleDbCommand cmd = new OleDbCommand();
- cmd.Connection = conn;
- string strSql = "select UserID,Context from Letter_Info order by ID desc";
- cmd.CommandText = strSql;
- cmd.CommandType = CommandType.Text;
- DataSet ds = new DataSet();
- try
- {
- conn.Open();
- OleDbDataAdapter adapt = new OleDbDataAdapter(strSql, conn);
- adapt.SelectCommand = cmd;
- adapt.Fill(ds, "Letter_Info");
- }
- catch (Exception ex)
- {
- Response.Write("数据库错误,错误原因:" + ex.Message);
- Response.End();
- }
- finally
- {
- conn.Close();
- }
- return ds;
- }
复制代码
2、设置GridView的数据源,显示数据 - public void fillGridView()
- {
- DataSet ds = new DataSet();
- ds = GetData();
- GridView1.DataSource = ds;
- GridView1.DataKeyNames = new string[] { "UserID" };
- GridView1.DataBind();
- getRefSet(ds);
- }
复制代码
3、窗体启动是调用fillGridView方法 - protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- fillGridView();
- }
- }
复制代码
效果图
来源:https://blog.csdn.net/cxh6863/article/details/80441527 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |