找回密码
 会员注册
查看: 137|回复: 0

asp.net中gridview的绑定数据源实现增删改查

[复制链接]

250

主题

1

回帖

819

积分

管理员

积分
819
发表于 2024-2-29 08:40:42 | 显示全部楼层 |阅读模式

gridview还是比较灵活的,有一种类似于excel的用法,可以直接在表格中进行添加,修改等操作。单元格数据比较段的表格用起来很方便。

可以参考https://blog.csdn.net/yingzhaom/article/details/50614599

我在这基础上改成了点击按钮弹出模态框进行操作。如有此类需求可以参考我的代码。

先从绑定数据源开始。

页面加载时绑定数据(可以把数据库连接封装,后面会多次使用):

  1. //数据库连接
  2. SqlConnection sqlcon;
  3. SqlCommand sqlcom;
  4. string strCon = "Data Source=(local);Database=数据库名;Uid=帐号;Pwd=密码";
  5. protected void Page_Load(object sender, EventArgs e)
  6. {
  7. if (!IsPostBack)
  8. {
  9. //初始化table
  10. bind_gv();
  11. }
  12. }
  13. protected void bind_gv()
  14. {
  15. string sqlstr = "select * from 表";
  16. sqlcon = new SqlConnection(strCon);
  17. SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
  18. DataSet myds = new DataSet();
  19. sqlcon.Open();
  20. myda.Fill(myds, "表");
  21. gvTag.DataSource = myds;
  22. gvTag.DataKeyNames = new string[] { "tid" };
  23. gvTag.DataBind();
  24. sqlcon.Close();
  25. }
复制代码

前端代码(表中列的dataField与查询的列名对应):

  1. <asp:GridView ID="gvTag" runat="server" AutoGenerateColumns="False" AllowSorting="True" CssClass="table table-striped" AllowPaging="True" OnPageIndexChanging="gvTag_PageIndexChanging" OnDataBound="gvTag_DataBound" PageSize="10" >
  2. <Columns>
  3. <asp:BoundField DataField="TID" HeaderText="Tag序号" ReadOnly="true" Visible="False" />
  4. <asp:BoundField DataField="GROUPCODE" HeaderText="Group" ReadOnly="true" ItemStyle-Width="70" />
  5. <asp:BoundField DataField="ELEMENTCODE" HeaderText="Element" ReadOnly="true" ItemStyle-Width="70" />
  6. <asp:BoundField DataField="TAGNAME" HeaderText="TagName" ReadOnly="true" ItemStyle-Width="260" />
  7. <asp:BoundField DataField="VID" HeaderText="VR序号" ReadOnly="true" Visible="False" />
  8. <asp:BoundField DataField="VRCode" HeaderText="VR" ReadOnly="true" ItemStyle-Width="50" />
  9. <asp:BoundField DataField="NOTES" HeaderText="描述" ReadOnly="true" />
  10. <asp:TemplateField HeaderText="操作" ItemStyle-Width="80" >
  11. <ItemTemplate>
  12. <asp:LinkButton ID="Modify" runat="server" CausesValidation="False" CommandArgument='<%# Eval("tid") %>' OnClick="Modify_Click" Text="编辑"></asp:LinkButton>
  13. <asp:LinkButton ID="Delete" runat="server" CausesValidation="False" CommandArgument='<%# Eval("tid") %>' OnClientClick="javascript:return confirm('确认要删除吗?')" AlternateText="删除此条目" OnCommand="Delete_Click" Text="删除"></asp:LinkButton>
  14. </ItemTemplate>
  15. </asp:TemplateField>
  16. </Columns>
  17. <PagerSettings Mode = "NextPreviousFirstLast" FirstPageText = "第一页" LastPageText = "末页" />
  18. <PagerTemplate>
  19. <table width="100%">
  20. <tr>
  21. <td width="75%">
  22. <asp:ImageButton ID="imgBtnFirst" runat="server" CommandArgument="First" CommandName="Page"
  23. ImageUrl="~/Images/First.png" ToolTip="第一页" />
  24. <asp:ImageButton ID="imgBtnPrev" runat="server" CommandArgument="Prev" CommandName="Page"
  25. ImageUrl="~/Images/Previous.png" ToolTip="上一页" />
  26. <asp:ImageButton ID="imgBtnNext" runat="server" CommandArgument="Next" CommandName="Page"
  27. ImageUrl="~/Images/Next.png" ToolTip="下一页" />
  28. <asp:ImageButton ID="imgBtnLast" runat="server" CommandArgument="Last" CommandName="Page"
  29. ImageUrl="~/Images/Last.png" ToolTip="最后页" />
  30. </td>
  31. <td align="right" width="25%">
  32. 页数:<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>
  33. </td>
  34. </tr>
  35. </table>
  36. </PagerTemplate>
  37. </asp:GridView>
复制代码

分页后台代码:

  1. protected void gvTag_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
  2. {
  3. gvTag.PageIndex = e.NewPageIndex;
  4. bind_gv();
  5. }
  6. protected void gvTag_DataBound(object sender, EventArgs e)
  7. {
  8. // 取得显示页数的那一列。
  9. GridViewRow pagerRow = gvTag.BottomPagerRow;
  10. if (pagerRow != null)
  11. {
  12. // 取得显示目前所在页数的 Label 控件。
  13. Label pageLabel = (Label)(pagerRow.Cells[0].FindControl("lblCurrentPage"));
  14. // 取得 第一页、上一页、下一页、最后页 的按钮。
  15. ImageButton imgBtnFirst =
  16. (ImageButton)(pagerRow.Cells[0].FindControl("imgBtnFirst"));
  17. ImageButton imgBtnPrev =
  18. (ImageButton)(pagerRow.Cells[0].FindControl("imgBtnPrev"));
  19. ImageButton imgBtnNext =
  20. (ImageButton)(pagerRow.Cells[0].FindControl("imgBtnNext"));
  21. ImageButton imgBtnLast =
  22. (ImageButton)(pagerRow.Cells[0].FindControl("imgBtnLast"));
  23. // 设定何时应该显示 第一页、上一页、下一页、最后页 的按钮。
  24. if (gvTag.PageIndex == 0)
  25. {
  26. imgBtnFirst.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  27. imgBtnPrev.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  28. }
  29. else if (gvTag.PageIndex == gvTag.PageCount - 1)
  30. {
  31. imgBtnLast.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  32. imgBtnNext.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  33. }
  34. else if (gvTag.PageCount <= 0)
  35. {
  36. imgBtnFirst.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  37. imgBtnPrev.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  38. imgBtnNext.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  39. imgBtnLast.Style.Add(HtmlTextWriterStyle.Visibility, "hidden");
  40. }
  41. if (pageLabel != null)
  42. {
  43. // 计算目前所在的页数。
  44. int currentPage = gvTag.PageIndex + 1;
  45. pageLabel.Text = currentPage.ToString() +
  46. " / " + gvTag.PageCount.ToString();
  47. }
  48. }
  49. }
复制代码

前台弹框代码:

  1. <!--编辑-->
  2. <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  3. <div class="modal-dialog" role="document">
  4. <div class="modal-content">
  5. <div class="modal-header">
  6. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  7. <h4 class="modal-title" id="exampleModalLabel">编辑</h4>
  8. </div>
  9. <div class="modal-body">
  10. <asp:TextBox type="text" ID="TidEdit" runat="server" Visible="False"></asp:TextBox>
  11. <div class="form-group">
  12. <label for="TagEdit" class="control-label">Tag:</label>
  13. <asp:TextBox type="text" class="form-control" ID="TagEdit" runat="server" ReadOnly="True"></asp:TextBox>
  14. </div>
  15. <div class="form-group">
  16. <label for="TagNameEdit" class="control-label">TagName:</label>
  17. <asp:TextBox type="text" class="form-control" ID="TagNameEdit" runat="server"></asp:TextBox>
  18. </div>
  19. <div class="form-group">
  20. <label for="NotesEdit" class="control-label">描述:</label>
  21. <asp:TextBox type="text" class="form-control" ID="NotesEdit" runat="server" TextMode="MultiLine" Height="80px"></asp:TextBox>
  22. </div>
  23. <div class="form-group">
  24. <label for="ddlVREdit" class="control-label">VR:</label>
  25. <asp:DropDownList ID="ddlVREdit" runat="server" Height="34px"></asp:DropDownList>
  26. </div>
  27. </div>
  28. <div class="modal-footer">
  29. <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
  30. <asp:Button ID="SaveEdit" type="button" class="btn btn-primary" runat="server" Text="保存" OnClick="SaveEdit_Click" />
  31. </div>
  32. </div>
  33. </div>
  34. </div>
复制代码

后台弹框和编辑代码(里面的dao和impl是封装的数据库连接和更新的代码,TagInfo是封装的实体类):

  1. //编辑弹框弹出
  2. protected void Modify_Click(object sender, EventArgs e)
  3. {
  4. LinkButton link = sender as LinkButton;
  5. int index = Convert.ToInt32(link.CommandArgument);
  6. TagInfoDao tag = new TagInfoDaoImpl();
  7. TagInfo tagInfo = tag.findByTid(index);
  8. //赋值
  9. TidEdit.Text = index.ToString();
  10. TagEdit.Text = tagInfo.groupCode +","+ tagInfo.elementCode;
  11. TagNameEdit.Text = tagInfo.tagName;
  12. NotesEdit.Text = tagInfo.notes;
  13. //弹出模态框
  14. ClientScriptManager scriptManager = ((Page)System.Web.HttpContext.Current.Handler).ClientScript;
  15. scriptManager.RegisterStartupScript(typeof(string), "", "$('#editModal').modal('show');", true);
  16. //查询
  17. VRInfoDao vr = new VRInfoDaoImpl();
  18. List<VRInfo> vrList = vr.findVRInfo("");
  19. ddlVREdit.DataSource = vrList;
  20. ddlVREdit.DataTextField = "code";
  21. ddlVREdit.DataValueField = "VID";
  22. ddlVREdit.DataBind();
  23. ddlVREdit.SelectedIndex = tagInfo.vid - 1;
  24. }
  25. //编辑保存
  26. protected void SaveEdit_Click(object sender, EventArgs e)
  27. {
  28. TagInfo tag = new TagInfo();
  29. tag.tid = Convert.ToInt32(TidEdit.Text);
  30. tag.groupCode = TagEdit.Text.Split(',')[0];
  31. tag.elementCode = TagEdit.Text.Split(',')[1];
  32. tag.tagName = TagNameEdit.Text;
  33. tag.notes = NotesEdit.Text;
  34. tag.vid = Convert.ToInt32(ddlVREdit.SelectedValue);
  35. TagInfoDao tagDao = new TagInfoDaoImpl();
  36. if (tagDao.updata(tag))
  37. {
  38. Alert("修改成功!");
  39. }
  40. else
  41. {
  42. Alert("修改失败!");
  43. }
  44. bind_gv();
  45. }
复制代码

Alert弹框代码:

  1. public void Alert(string str_Message)
  2. {
  3. ClientScriptManager scriptManager = ((Page)System.Web.HttpContext.Current.Handler).ClientScript;
  4. scriptManager.RegisterStartupScript(typeof(string), "", "alert('" + str_Message + "');", true);
  5. }
复制代码

删除后台代码:

  1. //删除
  2. protected void Delete_Click(object sender, EventArgs e)
  3. {
  4. LinkButton link = sender as LinkButton;
  5. int index = Convert.ToInt32(link.CommandArgument);
  6. TagInfoDao tag = new TagInfoDaoImpl();
  7. if (tag.delete(index))
  8. {
  9. //删除成功
  10. Alert("删除成功");
  11. }
  12. else
  13. {
  14. //删除失败
  15. Alert("删除失败");
  16. }
  17. bind_gv();
  18. }
复制代码

新增跟编辑一样就不放代码了。


来源:https://blog.csdn.net/ab17171313/article/details/81504755
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 13:01 , Processed in 0.774305 second(s), 26 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表