DataGrid 功能实现收集(二)

来源:互联网 发布:护眼助手软件 编辑:程序博客网 时间:2024/05/17 04:11

datagrid中打开新窗体

DataGrid1.Attributes.Add("onclick","window.open('Print_GoodsMove.aspx?GoodsMove_ID=" + Apply_ID + "','newwindow', 'height=600, width=745, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');"); 

跨页面实现多选

SelectMultiPages.aspx

<%@ Page EnableViewState="true" CodeBehind="SelectMultiPages.aspx.cs" Language="c#" 

AutoEventWireup="false" Inherits="eMeng.Exam.SelectMultiPages" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<title>跨页面实现多选</title>

<META http-equiv="content-type" content="text/html; charset=gb2312">

<style>

* {}{FONT-SIZE:12PX}

#Status {}{text-align:left}

</style>

<script language="JAVASCRIPT">

function AddRemoveValues(oChk) 

//在处理这个地方需要注意的是:你保存的值应该具有唯一性,这样才能不会替换错误的项。

if(oChk.checked)

SelectMultiPage.HdnSelectedValues.value += "," + oChk.value; 

else

SelectMultiPage.HdnSelectedValues.value = SelectMultiPage.HdnSelectedValues.value.replace("," + oChk.value,""); 

}

</script>

</HEAD>

<BODY>

<form id="SelectMultiPage" runat="server">

<asp:datagrid id="DataGrid1" HorizontalAlign="Center" AutoGenerateColumns="False" Width="600px"

        AllowPaging="True" runat="server">

    <AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>

    <HeaderStyle BackColor="#AAAADD" Font-Bold="True" HorizontalAlign="Center"></HeaderStyle>

    <PagerStyle HorizontalAlign="Right" Mode="NumericPages" Visible="True"></PagerStyle>

    <Columns>

        <asp:TemplateColumn HeaderText="选择">

            <ItemTemplate>

                <input type="checkbox" runat="server" id="chkSelect" onclick="AddRemoveValues(this)"

                    value='<%#DataBinder.Eval(Container.DataItem,"Title")%>'/>

            </ItemTemplate>

        </asp:TemplateColumn>

        <asp:TemplateColumn HeaderText="文章标题">

            <ItemTemplate>

                <asp:Literal Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>' runat="server" ID="TitleShow"/>

            </ItemTemplate>

        </asp:TemplateColumn>

        <asp:TemplateColumn HeaderText="发布时间">

            <ItemTemplate>

                <asp:Literal Text='<%# DataBinder.Eval(Container.DataItem, "CreateDate").ToString() %>' runat="server"/>

            </ItemTemplate>

        </asp:TemplateColumn>

    </Columns>

</asp:datagrid>

<div align=center>

<asp:button id="Button1" runat="server" Text="得到所选的值"></asp:button>

<div id="Status">

<asp:label id="Label1" runat="server"></asp:label>

</div>

<INPUT id="HdnSelectedValues" type="hidden" name="HdnSelectedValues" runat="server">

</div>

</form>

</BODY>

</HTML>

SelectMultiPages.aspx.cs

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.OleDb;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace eMeng.Exam

{

/**//// <summary>

/// SelectMultiPages 的摘要说明。

/// </summary>

public class SelectMultiPages : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Button Button1;

protected System.Web.UI.WebControls.Label Label1;

protected System.Web.UI.HtmlControls.HtmlInputHidden HdnSelectedValues;

protected System.Web.UI.WebControls.DataGrid DataGrid1;

private void Page_Load(object sender, System.EventArgs e)

{

    // 在此处放置用户代码以初始化页面

    if(!Page.IsPostBack)

    BindData();

}

private void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)

{

    DataGrid1.CurrentPageIndex = e.NewPageIndex;

    BindData(); 

}

void BindData()

{

    OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" 

        + HttpContext.Current.Server.MapPath("aspx.mdb"));

    OleDbDataAdapter da = new OleDbDataAdapter("Select Title, CreateDate from Document",cn);

    DataSet ds = new DataSet();

    da.Fill(ds);

    DataGrid1.DataSource= ds;

    DataGrid1.DataBind();

}

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

{

    //重新显示所选择的项目

    if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

    {

        if(HdnSelectedValues.Value.IndexOf(((Literal)e.Item.Cells[1].FindControl("TitleShow")).Text) >= 0 )

        {

            HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)(e.Item.Cells[0].FindControl("ChkSelect"));

            ChkSelected.Checked = true;

        }

    }

}

private void Button1_Click(object sender, System.EventArgs e)

{

    //为了显示的方便进行替换的

    Label1.Text = HdnSelectedValues.Value.Replace(",","<li>");

}

Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码

override protected void OnInit(EventArgs e)

{

    //

    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。

    //

    InitializeComponent();

    base.OnInit(e);

}

/**//// <summary>

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。

/// </summary>

private void InitializeComponent()

{    

    this.DataGrid1.ItemDataBound += 

        new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);

    this.DataGrid1.PageIndexChanged += 

        new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);

    this.Button1.Click += new System.EventHandler(this.Button1_Click);

    this.Load += new System.EventHandler(this.Page_Load);

}

#endregion    

}

}

如何给DataGrid添加自动增长列

我们用Northwind数据库做例子:

html页面的DataGrid如下所示:

<asp:datagrid id="grdTest" runat="server" Height="228px" Width="262px" AutoGenerateColumns="False" AllowPaging="True">

     <Columns>

      <asp:TemplateColumn>

       <ItemTemplate>

<!-- 这里是关键-->

        <SPAN>

          <%# Container.ItemIndex+1 %></SPAN>

       </ItemTemplate>

      </asp:TemplateColumn>

      <asp:BoundColumn DataField="CategoryName"></asp:BoundColumn>

      <asp:BoundColumn DataField="Description"></asp:BoundColumn>

     </Columns>

    </asp:datagrid>

下面我们可以写他的后台代码cs的文件了我们在它的Page_Load里面添加绑定方法如下所示:

private void Page_Load(object sender, System.EventArgs e)

  {

   // 在此处放置用户代码以初始化页面

   strConnection = ConfigurationSettings.AppSettings["sa"].ToString();

   myConnection = new SqlConnection(strConnection);

   SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT CategoryName, Description FROM Categories",myConnection);

// 为了分页方便ds是一个全局的变量

   myAdapter.Fill(ds);

   this.grdTest.DataSource = ds.Tables[0].DefaultView;

   this.grdTest.DataBind();

}

从上面的过程可以看出我们使用的是表Categories,这样我们就可以产生一列自增长的列,此列是从1开始的。如果我们想要一个从0开始的列有该怎么办呢?我们可以把<!-- 这里是关键-->下面的<span>里面的东西换成<asp:Label id=lblRowNumber runat="server" Text='<%# DataBinder.Eval(Container, "ItemIndex", "{0}") %>'>就可以了。

如果我们想要实现分页也显示的方法我们将使用DataTable的方法来实现,首先我们将DataGrid的列全部变成绑定列(为了方便演示,不是必须)。如下所示:

<asp:table id="tbData" runat="server" BackColor="LightSteelBlue" Height="13px" Width="16px" Font-Names="宋体" Font-Name="宋体" Font-Size="8pt" CellPadding="1" CellSpacing="0" BorderColor="black" BorderWidth="1" Gridlines="Both"></asp:table><br/>

    <asp:datagrid id="grdTest" runat="server" Height="228px" Width="262px" AutoGenerateColumns="False" PageSize="2" AllowPaging="True">

     <Columns>

      <asp:BoundColumn DataField="RowNumber" HeaderText="RowNumber"></asp:BoundColumn>

      <asp:BoundColumn DataField="CategoryName"></asp:BoundColumn>

      <asp:BoundColumn DataField="Description"></asp:BoundColumn>

     </Columns>

    </asp:datagrid>

在后台我们添加一个函数:

private DataTable GetRowNumberTable(DataTable dt){

   DataColumn col = new DataColumn("RowNumber",Type.GetType("System.Int32"));

   dt.Columns.Add(col);

   for(int i = 0;i<=dt.Rows.Count-1;i++){

    if(0 == i) 

     dt.Rows[i][col] = 1;

    else 

     dt.Rows[i][col] = Convert.ToInt32(dt.Rows[i-1][col]) +1;

   }

   return dt;

  }

然后我们将原来数据源改成如下:

this.grdTest.DataSource = this.GetRowNumberTable(ds.Tables[0]).DefaultView;

这样一来即使分页,数字也是连续的,并且将编号应用于所有的行而不是当前这一页的行。

在多线程里查询数据库并填充dataGrid

 在查询大数据量时,窗体界面会不动,“正在查询”的提示也不能显示。所以打算用多线程来实现,

可是当在线程里面执行到 this.dataGridDF.DataSource=dt.DefaultView;填充数据

时却提示报错,说什么该线程不能调用主线程创建的控件等等。

后来查了许多资料,终于搞定。可以在查询数据库时操作别的了,“正在查询”的提示也显示了。 

 

//或者在前面用一个线程查询,在线程里调用dataGrid.BeginInvoke(异步方法)来单独填充

 

  public delegate void myDelegate();

  DataTable dt;

 

  private void btnDianJia_Click(object sender, System.EventArgs e)

  {

   try

   {

    mythread = new Thread(new ThreadStart(ThreadWork));

    mythread.Start();    

   }

   catch(System.Exception ex)

   {

    MessageBox.Show(this,ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

   }   

  }

 

  void ThreadWork()

  {

   this.dataGridDJ.CaptionText="正在查询电价数据";

   mf.statusBarPanel1.Text="正在查询电价数据";

   this.Cursor=Cursors.WaitCursor;

 

   string shijian=this.dateTimeDianJia.DateValue;

   DateTime today=DateTime.Today;

   string mingcheng=this.txtMingCheng.Text;

   string leibie=this.cmbBoxLiebie_DJ.SelectedValue.ToString();

   PowerWeb.BLL.DianFeiDianJia.DianJia dj=new PowerWeb.BLL.DianFeiDianJia.DianJia();

 

   if(shijian==today.ToString("yyyyMM"))

   {

    dt=dj.GetList(leibie,mingcheng).Tables[0];

   }

   else

   {

    dt=dj.GetListOld(leibie,mingcheng,shijian).Tables[0];

   }

   this.dataGridDJ.CaptionText=shijian+"电价信息 (共计条"+dt.Rows.Count.ToString()+"记录)";

 

   dataGridDJ.BeginInvoke(new myDelegate(FillData));//异步调用(来填充)

   

   this.Cursor=Cursors.Default;

   mf.statusBarPanel1.Text="查询结束";

  }

  

  private void FillData()

  {

   this.dataGridDJ.DataSource=dt.DefaultView;

  }