注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

扶红星的博客

生活本无味,尝试的多了也便五味俱全了。

 
 
 

日志

 
 

gridview数据加载涉及知识点  

2013-02-28 12:45:31|  分类: 知识梳理 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

一.在前台设计页面中实现:

<asp:TextBox ID="userpic" runat="server"></asp:TextBox>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button10" runat="server" Text="上传" onclick="Button10_Click" />


<asp:GridView ID="GridView1" runat="server" AllowPaging="True"  AutoGenerateColumns="False" OnDataBound="GridView1_DataBound" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="3" onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">

                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox2_CheckedChanged" />
                                    选择项
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" />
                                </ItemTemplate>
                            </asp:TemplateField>

                            <asp:TemplateField>
                                <HeaderTemplate>图片</HeaderTemplate>
                                <ItemTemplate>
                                    <%--<asp:Image ID="Image1" runat="server" Width="20px"/>--%>
                                    <img src='http://fhx900808.blog.163.com/blog/<%#Eval("pic_path") %>' alt="你好" align="left" height="50" width="50" />
                                </ItemTemplate>
                              </asp:TemplateField>
                            <asp:BoundField HeaderText="编号" DataField="Id"/>//Visible="false"属性使得该列不显示,ReadOnly="True"使得该列在编辑时不变成文本框形式,即不可更改
                            <asp:BoundField HeaderText="采购员" DataField="Saler"/>
                            <asp:BoundField HeaderText="面辅料名称" DataField="GoodsName"/>
                            <asp:BoundField HeaderText="款号" DataField="StyleNumber"/>
                            <asp:BoundField HeaderText="计划数" DataField="PlanSaleNum"/>
                            <asp:BoundField HeaderText="供应商" DataField="Supplier"/>
                            <asp:BoundField HeaderText="采购周期" DataField="Period"/>
                            <asp:BoundField HeaderText="起订数" DataField="BeginNum"/>
                            <asp:BoundField HeaderText="本次采购" DataField="NowSaleNum"/>
                            <asp:BoundField HeaderText="备注" DataField="Explains"/>
                            <%--<asp:TemplateField>
                                <HeaderTemplate>图片</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Image ID="Image1" runat="server" Width="20px"/>
                                </ItemTemplate>
                            </asp:TemplateField>--%>
                        </Columns>

?

?<PagerTemplate>
        <br />
         <asp:Label ID="lblPage" runat="server" Text='<%# "+ (((GridView)Container.NamingContainer).PageIndex + 1)  + "页/共" + (((GridView)Container.NamingContainer).PageCount) + "" %> '></asp:Label>
         <asp:LinkButton ID="lbnFirst" runat="Server" Text="首页"  Enabled='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>' CommandName="Page" CommandArgument="First" ></asp:LinkButton>
        <asp:LinkButton ID="lbnPrev" runat="server" Text="上一页" Enabled='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>' CommandName="Page" CommandArgument="Prev"  ></asp:LinkButton>
        <asp:LinkButton ID="lbnNext" runat="Server" Text="下一页" Enabled='<%# ((GridView)Container.NamingContainer).PageIndex != (((GridView)Container.NamingContainer).PageCount - 1) %>' CommandName="Page" CommandArgument="Next" ></asp:LinkButton>
         <asp:LinkButton ID="lbnLast" runat="Server" Text="尾页"   Enabled='<%# ((GridView)Container.NamingContainer).PageIndex != (((GridView)Container.NamingContainer).PageCount - 1) %>' CommandName="Page" CommandArgument="Last" ></asp:LinkButton>
         到第<asp:TextBox runat="server" ID="inPageNum" Width="25px"& gt;</asp:TextBox> 页 <asp:Button ID="Button1" CommandName="go" runat="server" Text="跳转"  />
         <br />
     </PagerTemplate>?
                    </asp:GridView>

?

         <asp:Button ID="Button4" runat="server" Text="前一页" OnClick="Button4_Click"/>
         <asp:Button ID="Button5" runat="server" Text="后一页" OnClick="Button5_Click"/>
          <asp:DropDownList ID="Dr" runat="server" AutoPostBack="True" OnSelectedIndexChanged="Dr_SelectedIndexChanged">
                    </asp:DropDownList>

二、后台知识点运用:

1.将数据表中的数据绑定到gridview

publict DataTable GetData1(string sql)

{

        MySqlConnection conn = new MySqlConnection();
        string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["ArtkaBaisonConnString1"].ConnectionString;

       (// 配置文件中添加一个连接字符 串:<add name="ArtkaBaisonConnString1" connectionString="server=127.0.0.1; userid=root;database=test;port=3306;Allow Zero Datetime=True;"></add>
        conn.ConnectionString = connstr;
        conn.Open();
        DataSet dt = new DataSet();
        MySqlDataAdapter sda = new MySqlDataAdapter(sql,conn);
        sda.Fill(dt);

        return dt.Tables[0];

}

 public static int GetData2(string sql)
{
            SqlConnection conn = new SqlConnection();
           //string connStr = System.Configuration.ConfigurationManager.AppSettings["connStr"];//sql server连接字符串

            string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["ArtkaBaisonConnString1"].ConnectionString;       (// 配置文件中添加一个连接字符 串:<add name="ArtkaBaisonConnString1" connectionString="server=127.0.0.1; userid=root;database=test;port=3306;Allow Zero Datetime=True;"></add>
            conn.ConnectionString = connStr;
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            try
            {
                return cmd.ExecuteNonQuery();
            }
            catch
            {
                return -2;
            }
            finally
            {
                conn.Close();
            }
 }

public void GetTable()

{

            this.GridView1.HeaderStyle.BackColor = Color.DarkGray;
            string sql = "select sku_id....from ...";
            DataTable dt = sqlHelp.GetData1(sql);
            this.GridView1.DataSource = dt;
            this.GridView1.DataKeyNames = new string[] { "sku_id" };
            this.GridView1.DataBind();

}

2.触发全选复选框事件

        //先实例化出一个GridView1里的CheckBox2
        CheckBox checkbox2 = (CheckBox)GridView1.HeaderRow.FindControl("CheckBox2");
        //或是 CheckBox checkBox2 = (CheckBox)sender;
        //再利用循环读出GridView1里的所有行,然后再实例化出一个GridView1里的CheckBox1,当CheckBox2被选中的同时CheckBox1也被选中
       for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox checkbox1 = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            checkbox1.Checked = checkbox2.Checked;
        }

3.上传、保存本地图片到工程项目文件夹中继而加载到预先设定的控件中

        string ext = FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf('.')).ToLower();//获取从本地上传的图片的格式名
        if (ext != ".jpg" && ext != ".bmp" && ext != ".png")
        {
            Response.Write("<script>alert('只能上传.jpg或.bmp或.png文件');history.go(-1);</script>");
            return;
        }

       string fileName = GridView1.Rows[0].Cells[1].Text.ToString() + ext;
        userpic.Text = fileName;
        fileName = Request.PhysicalApplicationPath + "图片\\" + fileName;
        FileUpload1.SaveAs(fileName);//将上传的图片自定义名称保存到项目工程的预定图片文件夹里

        Image a = (Image)GridView1.Rows[0].FindControl("Image1");
        int ss = Convert.ToInt32(GridView1.Rows[0].Cells[1].Text.ToString());
        a.ImageUrl = string.Format("~/图片/{0}.jpg", ss);//加载图片到预定的控件里面

4.分页加载查看数据

//触发下拉框选择分页事件
    protected void Dr_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.GridView1.PageIndex = this.Dr.SelectedIndex;
        GetTable();//加载数据方法略
    }
   //触发gridview中的分页事件
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GetTable();//加载数据方法略

        TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum");
        tb.Text = (GridView1.PageIndex + 1).ToString();
    }
    //控件绑定的时候根据分页数填充下拉框分页模式
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        this.Dr.Items.Clear();
        for (int i = 0; i < this.GridView1.PageCount; i++)
        {
            int num2 = i + 1;
            ListItem item = new ListItem(num2.ToString(), num2.ToString());
            this.Dr.Items.Add(item);
        }
        if (this.Dr.Items.Count > 0)
        {
            this.Dr.SelectedIndex = this.GridView1.PageIndex;
        }
    }

//触发前一页按钮事件
    protected void Button4_Click(object sender, EventArgs e)
    {
        if (this.GridView1.PageIndex > 0)
        {
            this.GridView1.PageIndex--;
        }
        GetTable();//加载数据方法略
    }
   //触发后一页按钮事件
    protected void Button5_Click(object sender, EventArgs e)
    {
        if (this.GridView1.PageIndex < (this.GridView1.PageCount - 1))
        {
            this.GridView1.PageIndex++;
        }
        GetTable();//加载数据方法略
    }

5.触发编辑行事件

       //GridView1,sku行编辑

       protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.GridView1.EditIndex = e.NewEditIndex;
            GetTable();
        }
       //GridView1,sku行更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string skus = this.GridView1.DataKeys[e.RowIndex].Values[0].ToString();
            string selfcost = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[11].Controls[0])).Text.ToString();
            string spreadcost = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[12].Controls[0])).Text.ToString();
            string packagcost = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[13].Controls[0])).Text.ToString();
             string sqls = string.Format("update TB_Sku set  self_cost='{0}',spread_cost='{1}',packag_cost='{2}' where sku_id=" +  skus + "", selfcost, spreadcost, packagcost);
            if (Convert.ToInt32(sqlHelp.GetData2(sqls)) != -2)
            {
                GridView1.EditIndex = -1;
                GetTable();
                ClientScript.RegisterStartupScript(GetType(), "", "alert('恭喜你,编辑成功!');", true);
            }
        }
        //GridView1,sku行取消更新
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.GridView1.EditIndex = -1;
            GetTable();
        }

5.触发自定义分页事件

 //分页部分点击跳转按钮事件
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "go")
            {
                try
                {
                    TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum");
                    int num = Int32.Parse(tb.Text);
                    GridViewPageEventArgs ea = new GridViewPageEventArgs(num - 1);
                    GridView1_PageIndexChanging(null, ea);
                }
                catch
                {
                }
            }

        }

三、最终效果图如下

  评论这张
 
阅读(226)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017