Archive

Posts Tagged ‘Gridview’

GridView 排序 分页 编辑 删除 更新 模板 综合使用

June 13th, 2010 Tony hu No comments

这是我最近在做一个项目,我尽量全部手写代码。现在将CS文件贴分来分享一下,作一个备忘吧!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Capsugel.Web
{
public partial class Customers : System.Web.UI.Page
{
//使用DataView,排序的时候使用到
DataView dv = new DataView();

protected void Page_Load(object sender, EventArgs e)
{
//第一次加载页面
if (!IsPostBack)
{
bind();
}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//测试 Ajax
//System.Threading.Thread.Sleep(1000);
GridView1.PageIndex = e.NewPageIndex;
//重新绑定一次
bind();
}

///
/// 绑定GridView
///
void bind()
{
Capsugel.BLL.Customer bll = new BLL.Customer();
//根据TextBox中的关键词,显示数据
DataTable dt = bll.GetList_ByName(TextBox1.Text.Trim()).Tables[0];
if (ViewState["sortExpr"] != null)
{
dv = new DataView(dt);
dv.Sort = (string)ViewState["sortExpr"] + ” ” + ViewState["sortingOrder"].ToString();
}
else
{
dv = dt.DefaultView;
}
GridView1.DataSource = dv;
GridView1.DataBind();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int idx = 0;
string Uid = “”;
BLL.Customer bll = new BLL.Customer();

if (e.CommandName == “myedit”)
{
//得到当前行的索引号,确定要将哪一行开启编辑状态,
//如果是第二行的第一个,那应该是 0,所以才有了下面的公式
idx = Convert.ToInt32(e.CommandArgument)-GridView1.PageIndex * GridView1.PageSize;
GridView1.EditIndex = idx;
}
else if (e.CommandName == “myupdate”)
{
idx = Convert.ToInt32(e.CommandArgument) – GridView1.PageIndex * GridView1.PageSize;
Uid = GridView1.DataKeys[idx].Values[0].ToString();
//得到编辑框中的值
string uname = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox1″)).Text;
string custid = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox2″)).Text;
string userid = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox3″)).Text;
bool check = ((CheckBox)GridView1.Rows[idx].FindControl(“CheckBox1″)).Checked;
//对像模型
Model.Customer m = new Model.Customer();
m.CID = Convert.ToInt32(Uid);
m.Checked = check;
m.Name = uname;
m.CustID = custid;
m.Uid = userid;
//更新
bll.Update(m);
//取消编辑状态
GridView1.EditIndex = -1;
}
else if (e.CommandName == “mydelete”)
{
idx = Convert.ToInt32(e.CommandArgument) – GridView1.PageIndex * GridView1.PageSize;
Uid = GridView1.DataKeys[idx].Values[0].ToString();
bll.Delete(Convert.ToInt32(Uid));
}
else if (e.CommandName == “mycancel”)
{
GridView1.EditIndex = -1;
}
//最后都要进行重新绑定一次
bind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//判断是否是DataRow,以防止鼠标经过Header也有效果
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add(“onmouseover”, “e=this.style.backgroundColor;this.style.backgroundColor=’#BDF9AC’;”);
e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=e;”);
}
}

protected void Button3_Click(object sender, EventArgs e)
{
//POSTBACK
bind();
}

///
/// 处理排序的问题,定义的排序
///
///
///
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//点一次时是desc,第二次是asc
if (ViewState["sortingOrder"] == null)
ViewState["sortingOrder"] = “desc”;
else if (Convert.ToString(ViewState["sortingOrder"]) == “asc”)
ViewState["sortingOrder"] = “desc”;
else if (Convert.ToString(ViewState["sortingOrder"]) == “desc”)
ViewState["sortingOrder"] = “asc”;

ViewState["sortExpr"] = e.SortExpression;
bind();
}

///
/// 显示所有的,只要清空一下TextBox中的值
///
///
///
protected void Button4_Click(object sender, EventArgs e)
{
TextBox1.Text = “”;
bind();
}
}
}

Categories: ASP.net, Web Tags: , , , ,

ASP.net 中,自定义、填充 DataTable,GridView 显示

December 30th, 2009 Tony hu 1 comment

void bind()
{
DateTime dt1 = Convert.ToDateTime(this.DropDownList1.SelectedValue + “-” + this.DropDownList2.SelectedValue + “-1″);
DateTime dt2 = Convert.ToDateTime(this.DropDownList3.SelectedValue + “-” + this.DropDownList4.SelectedValue + “-1″);
int i = 0;
int j = 0;
j = Convert.ToInt32(DB.GetFirstValue(“Select Datediff(m,’” + dt1 + “‘,’” + dt2 + “‘) AS J;”, DB.connectionString)) + 1;
DataTable dt;
‘定义每一列的属性
DataTable Dt = new DataTable(“GetSummary”);
Dt.Columns.Add(“Date”, Type.GetType(“System.String”));
Dt.Columns.Add(“SORTING100″, Type.GetType(“System.Int32″));
Dt.Columns.Add(“HCMNOBYPASS”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“PCMNOBYPASS”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“REWORK”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“VCAPS”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“SUM”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“Total”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“Percent”, Type.GetType(“System.String”));
Dt.Columns.Add(“HCMNOBYPASSCC”, Type.GetType(“System.Int32″));
Dt.Columns.Add(“PCMNOBYPASSCC”, Type.GetType(“System.Int32″));
‘填充
for (i = 0; i < j; i++)
{
string date = dt1.AddMonths(i).ToShortDateString();
string tsql = “SELECT Count(f_LC_LotUID) AS Total FROM [t_Rel_LotCar] where Datediff(m,f_LC_ProdCalDate,’” + date + “‘)=0 and f_LC_CarStatus=’ST01/OK’”;

dt = NoPrintClass.GetGetSummary(date);
‘将从数据库中得到的表的各个列的值,填充到我们定义的变量Dt中,注意这里的 Dt 和 dt 是不一样的。这里是C#程序
Dt.Rows.Add(new object[] { dt.Rows[0][0], dt.Rows[0][1], dt.Rows[0][2], dt.Rows[0][3], dt.Rows[0][4], dt.Rows[0][5], dt.Rows[0][8], Convert.ToInt32(DB.GetFirstValue(tsql, DB.connWIP)), ‘2′, dt.Rows[0][6], dt.Rows[0][7] });
GridView1.DataSource = Dt;
GridView1.DataBind();
}
}

时间较紧,没有写注释,业内人应该都可以看懂

在GridView的RowCommand事件中获取Rowindex,即获得数据行所在页的索引号

September 8th, 2009 Tony hu No comments

先看一下我的后台代码:

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //得到行所在的索引号
            int idx = Convert.ToInt32(e.CommandArgument);
            //得到各个控件的值
            string id = GridView1.Rows[idx].Cells[0].Text;
            string txt_ArtworkNum = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox2″)).Text;
            string txt_RollNum = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox3″)).Text;
            string txt_Artwork = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox4″)).Text.Replace(“‘”, “””);
            string txt_ShelfAddress = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox5″)).Text;
            string txt_OrderQty = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox6″)).Text;
            string txt_Supplier = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox7″)).Text.Replace(“‘”,”””);
            string txt_StartDate = ((TextBox)GridView1.Rows[idx].FindControl(“TextBox1″)).Text;
//其它代码省略……
           

再看一下原先的前台代码

<ItemTemplate>
 <asp:Button ID=”Button3″ runat=”server” CausesValidation=”False”
CommandArgument=”<%# Container.DataItemIndex %>”
CommandName=”Entry” Text=”入库” OnClientClick=”return confirm(‘确认要将此钢轮移出备用库放入当前使用库吗?’)”/>
 </ItemTemplate>
 </asp:TemplateField>

最后看一下改进后的代码

<ItemTemplate>
 <asp:Button ID=”Button3″ runat=”server” CausesValidation=”False”
CommandArgument=”<%# ((GridViewRow) Container).RowIndex %>”
CommandName=”Entry” Text=”入库” OnClientClick=”return confirm(‘确认要将此钢轮移出备用库放入当前使用库吗?’)”/>
</ItemTemplate>
</asp:TemplateField>

其实就是为了说明一个问题:

如果用Container.DataItemIndex 在后台代码中得到的是这一数据行在这个数据表中的序列,如果此Gridview不分页的话,用起来没有任何问题,如果分页的话,就不行了。如我们操作的是第二页的第二条记录,得到的序列是 11 ,即 idx =11 ,而我期望的是1.

如果用((GridViewRow) Container).RowIndex 那 idx=1; 即这一行代码得到的是此数据行在当前Gridview页面中的序列,如果PageSize=10的话,那idx 最大为9,最小为0.

今天项目中用到的,特别记录一下.

Categories: ASP.net, Web Tags: ,

Gridview编辑状态下CheckBoxList和DropDownList数据绑定

July 3rd, 2009 Tony hu No comments

这两天老老大在泰国,我做的POP系统需要让我增加两个功能,其中就用到了在Gridview编辑状态下控件绑定数据库的问题,查询了相关资料后终于搞定了。将主要的代码写在这里,记录一下。

主要就是一个:
e.Row.RowState == DataControlRowState.Edit ||
            e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit
我觉得主要是用来判断Gridview的行的状态,之前没有加这个条件,所以一直是没有绑定到对象之类的错误提示。 

主要的代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //判断是否是DataRow,以防止鼠标经过Header也有效果
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //行的状态是: 编辑状态 或者 (交替行且是编辑状态)
        if (e.Row.RowState == DataControlRowState.Edit ||
            e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit)
            )
        {
            //下面是绑定CheckBoxList,根据Gridview中的显示的值,更改CheckBoxList的选中状态
            Label lab = (Label)e.Row.FindControl(“TxtPrinter”);
            CheckBoxList chk = (CheckBoxList)e.Row.FindControl(“OperatorList”);                   
            string txtPrinter = lab.Text;
            if (txtPrinter != “”)
            {
                for (int i = 0; i < chk.Items.Count; i++)
                {
                    if (txtPrinter.IndexOf(chk.Items[i].Text.ToString()) >= 0)
                    {
                        chk.Items[i].Selected = true;
                    }
                }
            }
            //下面是绑定DropDownList,根据Gridview Cells中显示的内容查找数据库,如果存在相关信息就显示DropDownList,并绑定
            DropDownList printroll = (DropDownList)e.Row.FindControl(“PrintRollList”);
            TextBox txt_printroll = ((TextBox)e.Row.FindControl(“txtPrintroll”));
            BLL.printroll bll = new BLL.printroll();
            string pid = bll.GetID(txt_printroll.Text.Trim());
            if (pid == “–”)
            {
                printroll.Visible = false;
            }
            else
            {
                DataTable dt = bll.GetChildList(Convert.ToInt32(pid));
                if (dt.Rows.Count != 0)
                {
                    printroll.DataSource = dt;
                    printroll.DataTextField = dt.Columns["printroll"].ToString();
                    printroll.DataValueField = dt.Columns["printroll"].ToString();
                    printroll.DataBind();

                    printroll.Items.Insert(0, “–PrintRoll–”);
                    printroll.Items[0].Value = “0″;
                    printroll.Visible = true;
                }
            }                   
        }
    }

}

Categories: ASP.net, Web Tags: