DataGrid小结

前台数据绑定:
<asp:Label id="id1" runat="server" text='<%# DataBinder.Eval(Container.DataItem,"autoid1") %>'></asp:Label>
<asp:Label id="question1" runat="server"><%# DataBinder.Eval(Container.DataItem,"question") %></asp:Label>

只有模板列才可以设置CommandNameCommandArgument
EditCommandDeleteCommand等事件激发之前,会先激发ItemCreated事件,

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e){}
函数中可以定义多个激发事件,只需在模板列中为不同控件设置相应的CommandNameCommandArgument参数,函数中在代码执行之前用if(e.CommandName)或者if(e.CommandArgument)判断命令来源

-------------------------------------------------------------
DataGrid
功能函数:

 

private void DataGrid1_EditCommand(object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
   DataGrid1.EditItemIndex=(int)e.Item.ItemIndex;

   //刷新页面
   string strConnection=System.Configuration.ConfigurationSettings.AppSettings["strConn"].ToString();
   string strSQL="select * from "+subjectTable+" ";    
   OleDbConnection objConnection=new OleDbConnection(strConnection);
   objConnection.Open();
   OleDbDataAdapter DaAd = new OleDbDataAdapter(strSQL,objConnection);
   DataSet DataSetUser = new DataSet();
   DaAd.Fill(DataSetUser,"user_info");
   DataGrid1.DataSource=DataSetUser.Tables["user_info"].DefaultView;
   DataGrid1.DataBind();
   DataSetUser.Dispose();
   objConnection.Close();   
}


点击“修改”按钮后,会出现很宽的TextBox,可以用以下代码设置TextBox的宽度:
private void DataGrid1_ItemDataBound(object sender,System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    if(e.Item.ItemType == ListItemType.EditItem)
    {
        TextBox t = (TextBox)e.Item.Cells[X].Controls[0];//X
改为具体列的列值
        t.Width = 80;
    }
}


private void DataGrid1_CancelCommand(object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
   DataGrid1.EditItemIndex=-1;

   //刷新页面
   string strConnection=System.Configuration.ConfigurationSettings.AppSettings["strConn"].ToString();
   string strSQL="select * from "+subjectTable+" ";      
   OleDbConnection objConnection=new OleDbConnection(strConnection);
   objConnection.Open();
   OleDbDataAdapter DaAd = new OleDbDataAdapter(strSQL,objConnection);
   DataSet DataSetUser = new DataSet();
   DaAd.Fill(DataSetUser,"user_info");
   DataGrid1.DataSource=DataSetUser.Tables["user_info"].DefaultView;
   DataGrid1.DataBind();
   DataSetUser.Dispose();
   objConnection.Close();  
}


private void DataGrid1_UpdateCommand(object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{   
   string userID = e.Item.Cells[0].Text;//
注意:前台要注明属性 ReadOnly="True"   
   string testID = e.Item.Cells[1].Text;   
   string score1=((TextBox)e.Item.Cells[2].Controls[0]).Text.ToString().Trim();
   string date1=((TextBox)e.Item.Cells[3].Controls[0]).Text.ToString().Trim();
   string score2=((TextBox)e.Item.Cells[4].Controls[0]).Text.ToString().Trim();
   string date2=((TextBox)e.Item.Cells[5].Controls[0]).Text.ToString().Trim();
   string score3=((TextBox)e.Item.Cells[6].Controls[0]).Text.ToString().Trim();
   string date3=((TextBox)e.Item.Cells[7].Controls[0]).Text.ToString().Trim();   
   string strConnection=System.Configuration.ConfigurationSettings.AppSettings["strConn"].ToString();
   string strSQL="update "+subjectTable+" set score1='"+score1+"',date1='"+date1+"',score2='"+score2+"',date2='"+date2+"',score3='"+score3+"',date3='"+date3+"'where userID='"+userID+"'"; 
   //Response.Write(strSQL);       
   OleDbConnection objConnection=new OleDbConnection(strConnection);
   objConnection.Open();
   OleDbCommand objCommand=new OleDbCommand(strSQL,objConnection);
   objCommand.ExecuteNonQuery();
   objConnection.Close();

   DataGrid1_CancelCommand(null,null);  
}

 

private void DataGrid1_DeleteCommand(object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{

  //当最后一页的记录被删除时,跳到前一页

  if((DataGrid1.Items.Count)%(DataGrid1.PageSize)==1)
   {
        DataGrid1.CurrentPageIndex=Math.Max(0,DataGrid1.CurrentPageIndex-1);
   }
   //DataGrid1.CurrentPageIndex=0;

   string questionid= e.Item.Cells[0].Text;   
   string strConnection=System.Configuration.ConfigurationSettings.AppSettings["strConn"].ToString();
   string strSQL="delete from single_select where questionID='"+questionid+"'"; 
   //Response.Write(strSQL);       
   OleDbConnection objConnection=new OleDbConnection(strConnection);
   objConnection.Open();
   OleDbCommand objCommand=new OleDbCommand(strSQL,objConnection);
   objCommand.ExecuteNonQuery();
   objConnection.Close();

   DataGrid1_CancelCommand(null,null);   
  }

 

private void DataGrid1_PageIndexChanged(object source,System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
   DataGrid1.CurrentPageIndex=e.NewPageIndex;  
   //
刷新页面
   string strConnection=System.Configuration.ConfigurationSettings.AppSettings["strConn"].ToString();
   string strSQL="select * from "+subjectTable+" ";      
   OleDbConnection objConnection=new OleDbConnection(strConnection);
   objConnection.Open();
   OleDbDataAdapter DaAd = new OleDbDataAdapter(strSQL,objConnection);
   DataSet DataSetUser = new DataSet();
   DaAd.Fill(DataSetUser,"user_info");
   DataGrid1.DataSource=DataSetUser.Tables["user_info"].DefaultView;
   DataGrid1.DataBind();
   DataSetUser.Dispose();
   objConnection.Close(); 
}

 

private void DataGrid1_SortCommand(object source,System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{

   //ViewState["SortField"]=e.SortExpression.ToString();获得点击的标头
   //dv.Sort=ViewState["SortField"].ToString();
对某一标头排序

   string strConnection=System.Configuration.ConfigurationSettings.AppSettings["strConn"].ToString();
   string strSQL="select * from user_inf";    
   //Response.Write(strSQL);
调试时查看语句是否正确     
   OleDbConnection objConnection=new OleDbConnection(strConnection);

   OleDbDataAdapter DaAd = new OleDbDataAdapter(strSQL,objConnection);
   DataSet DataSetUser = new DataSet();
   DaAd.Fill(DataSetUser,"user_inf");//
不替表格取名字,表格名字就默认为0
   DataView dv=DataSetUser.Tables["user_inf"].DefaultView;
   dv.Sort=e.SortExpression.ToString();//
对点击的标头排顺

   DataGrid1.DataSource=dv;
   DataGrid1.DataBind();
   DataSetUser.Dispose();//
释放DataSet


-------------------------------------------------------------

DataGrid中创建多表头:
private void DataGrid1_ItemCreated(object sender,System.Web.UI.WebControls.DataGridItemEventArgs e)
{
   if ( e.Item.ItemType == ListItemType.Header )
   {
    TableCellCollection tcl = e.Item.Cells;
    tcl.Clear();
    DataGridItem dgi =new DataGridItem(0,-1,ListItemType.Header);
    DataGridItem dgi1= new DataGridItem(0,-1,ListItemType.Header);
    Table tb = new Table();
    tb = (Table)DataGrid1.Controls[0];
    tb.Rows.AddAt(0,dgi);
    tb.Rows.AddAt(1,dgi1);

    TableCell tc11 = new TableCell();
    TableCell tc12 = new TableCell();
    TableCell tc13 = new TableCell();
    TableCell tc14 = new TableCell();
    TableCell tc15 = new TableCell();
    TableCell tc16 = new TableCell();
    TableCell tc17 = new TableCell();

    tc11.Text = "姓名";
    tc11.ColumnSpan = 1;
    tc11.RowSpan = 2;
    dgi.Cells.Add(tc11);

    tc12.Text = "密码";
    tc12.ColumnSpan = 1;
    tc12.RowSpan = 2;
    dgi.Cells.Add(tc12);

    tc13.Text = "成绩";
    tc13.ColumnSpan = 3;
    //tc13.RowSpan = 1;
    dgi.Cells.Add(tc13);

    
    tc14.Text = "
英语";
    tc14.ColumnSpan = 1;
    //tc14.RowSpan = 1;
    dgi1.Cells.Add(tc14);

    tc15.Text = "数学";
    tc15.ColumnSpan = 1;
    //tc15.RowSpan = 1;
    dgi1.Cells.Add(tc15);

    tc16.Text = "语文";
    tc16.ColumnSpan = 1;
    //tc16.RowSpan = 1;
    dgi1.Cells.Add(tc16);

    tc17.Text = "日期";
    tc17.ColumnSpan = 1;
    tc17.RowSpan = 2;
    dgi.Cells.Add(tc17);    

   }
}
---------------------------------------------------------------------------------
在每行“删除”按钮点击前弹出提示对话框:(也可为其他类型的激发事件弹出提示对话框,设置CommandName参数,并在ItemDataBound函数中判断命令来源)
DataGrid最后一行显示“合计”栏,对DataGrid中的各列进行合计。
*************问题:当DataGrid分页时,只会合计一页,更好的方法是直接利用DataSet****************
private void DataGrid1_ItemDataBound(object sender,System.Web.UI.WebControls.DataGridItemEventArgs e)
{
   //
点击"删除"按钮后弹出确认对话框
   if(e.Item.FindControl("btnDelete1")!=null)
   {
       ((LinkButton)e.Item.FindControl("btnDelete1")).Attributes.Add("onClick", "return confirm('
你确定要删除这一项吗?');");
   }

   //点击"提交合同"按钮后弹出确认对话框
   if(e.Item.FindControl("btnComplete1")!=null)
   {
       ((LinkButton)e.Item.FindControl("btnComplete1")).Attributes.Add("onClick", "return confirm('
你确定要将“会签中合同”提交为“已签定合同”吗?');");
   }


   //
DataGrid当前页面进行合计,并在最后一行显示“合计”行   
   if(e.Item.ItemType!=ListItemType.Header)
   {    
    try
    {
     sum1++;
    }
    catch
    {}

    try
    {
     sum2+=Convert.ToDouble(e.Item.Cells[3].Text.Trim());
    }
    catch
    {}

try
    {
     //sum3+=Convert.ToDouble(e.Item.Cells[3].Text.Trim());
     sum3+=(Convert.ToDouble(e.Item.Cells[3].Text.Trim()))*(Convert.ToDouble(e.Item.Cells[4].Text.Trim()))/100;
    }
    catch
    {}
   }
   if(e.Item.ItemType == ListItemType.Footer )
   {   
        
    //int PageCount = DGridJxjhzxqk.PageCount;
    //int CurPageIndex = DGridJxjhzxqk.CurrentPageIndex;    
    e.Item.Cells[0].Text = "
合计";
    e.Item.Cells[1].Text = "
共有"+sum1.ToString()+"个合同
";
    //
以“¥49.00的格式输出合计金额,若"C"改为"C6"输出为¥
49.000000
    e.Item.Cells[3].Text = sum2.ToString("C",System.Threading.Thread.CurrentThread.CurrentCulture);
    e.Item.Cells[4].Text = sum3.ToString("C",System.Threading.Thread.CurrentThread.CurrentCulture);    
   }


***
DataGrid中的所有绑定数据进行求和***
//
利用DataSet求和

DataTable dt=ds.Tables[TableName];
foreach(DataRow dr in dt.Rows)
{
 sum1++;
 double dunwei = Convert.ToDouble(dr["CLZZDW"].ToString().Trim()); //
载重吨位
 sum11 += dunwei;
 if((dunwei>=0)&&(dunwei<=5))  //
小于等于5
 {
  sum2++; //
该吨位的车辆数
  sum22 += dunwei; //
该吨位总数
 }
 if((dunwei>5)&&(dunwei<=15))
 {
  sum3++;
  sum33 += dunwei;
 }
 if((dunwei>15)&&(dunwei<=25))
 {
  sum4++;
  sum44 += dunwei;
 }
 if(dunwei>25)
 {
  sum5++;
  sum55 += dunwei;
 }
}
Label1.Text = "
统计:";
Label1.Text += "
车辆总数:"+sum1.ToString()+"<br>载重吨位总数
:"+sum11.ToString();    
Label1.Text += "<br>
5:<br>车辆数:"+sum2.ToString()+"<br>载重吨位总数
:"+sum22.ToString(); 
Label1.Text += "<br>5-15
:<br>车辆数:"+sum3.ToString()+"<br>载重吨位总数
:"+sum33.ToString();
Label1.Text += "<br>16-25
:<br>车辆数:"+sum4.ToString()+"<br>载重吨位总数
:"+sum44.ToString();
Label1.Text += "<br>
25:<br>车辆数:"+sum5.ToString()+"<br>载重吨位总数
:"+sum55.ToString();
----------------------------------------------------------
遍历DataGrid中的各行:

int i = 1;
Label Lbl;
foreach(DataGridItem dgi in DGridBjcgjh.Items)
   {       
    Lbl = (Label)dgi.FindControl("LblBjxh");
    Lbl.Text =Convert.ToString(DGridBjcgjh.CurrentPageIndex*DGridBjcgjh.PageSize+i);
    i++;
   }

 

----------------------------------------------------------------

----------------------------------------------------------------

水平滚动条<div style="OVERFLOW-X: scroll; WIDTH: 800px"></div>
--------------------------------------------------------
怎么让DataGrid单元格显示一个百分数出来
?
>>
你在Datagrid中属性里设置,那里有个数据格式设置表达式,{P},OK

>>
用模板列,绑定<%# DataBinder.Eval(container.DataItem,"字段名") & "%" %
>>
DataGrid_ItemDataBound里面设置

e.Item.Cells[0].Text = string.Format("{0, 5:P2}", Convert.ToDouble(e.Item.Cells[0].Text));

--------------------------------------------------------------------------
B/S,如果实现DataGrid锁定前几列?
>>
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{   //
假设DATAGRID只有列

   if (e.Item.ItemType==ListItemType.Header)
   {    
    for(int i=0; i<9 ; i++)
    {
     e.Item.Cells[i].Attributes.Add("Width","100");
    }
    //
能否拖放的关键一句
   }
   //
1,2
   e.Item.Cells[0].CssClass = "locked";
   e.Item.Cells[1].CssClass = "locked";
}

------------------------------------------------------------------------------
DataGrid
执行编辑命令后,出现TextBox,要怎么才能控制TextBox的长度?
>>
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    if(e.Item.ItemType == ListItemType.EditItem)
    {
        TextBox t = (TextBox)e.Item.Cells[X].Controls[0];//X
改为具体列的列值

        t.Width = 20;
    }
}
------------------------------------------------------------------------------
我想让整行都可以链接,而不是单独的某一列
也就是说,我把鼠标放到这行的任何一列都可以链接
(不要把每列都变成模板列吧?)
>>
要点:
datagriditemdatabound事件里面的itemattributes里面增加onclick事件,简单代码如下:
private void YourDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item  || e.Item.ItemType == ListItemType.AlternatingItem)
{
//
添加自定义属性,当鼠标移过来时设置该行的背景色为"6699ff",并保存原背景色
e.Item.Attributes.Add("onmouseover","currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");
//
添加自定义属性,当鼠标移走时还原该行的背景色
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=currentcolor");
e.Item.Attributes.Add("style","cursor:hand");
e.Item.Attributes.Add("onclick","YourScriptFunction()");
}
}

----------------------------------------------------------------------
asp.net
datagrid行的选定变色- -                                      

在使用asp.netdatagrid时,有时候需要选中一条记录,就是当鼠标拖到那一行,那一行就变颜色,这样很方便,也很显眼,尤其是那种在选中一条记录跳转或弹出新页面就更方便了,很遗憾asp.net中的datagrid,没有这样的功能,那只好代码实现了
方法如下:
datagridItemDataBound事件中加入:
if (e.Item.ItemIndex==-1) return;
//e.Item.Attributes.Add("bgcolor","#EFFFDA");
e.Item.Attributes.Add("style","cursor:hand");   e.Item.Attributes.Add("onMouseOver=this.style.backgroundColor","buttonface");
e.Item.Attributes.Add("onMouseOut=this.style.backgroundColor","");   e.Item.Attributes.Add("onclick","js:parent.window.open('new.aspx','')");  

这样,当你的鼠标拖到DATAGRID上那一行就可以看到当前行变了颜色,点击它就可以打开一个新页面,这些是借助javasript完成的,你也可以试试,很方便的。:)

-----------------
private void dgrdBb1_ItemDataBound(object sender,System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) || (e.Item.ItemType == ListItemType.SelectedItem) )
{
string BglJ = "#E7E7FF";
string BglO = "#F7F7F7";
e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='#ffebcd'");
if (e.Item.ItemIndex%2==1)
{
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor='"+BglO+"'");
}
else
{
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor='"+BglJ+"'");
}
}
}

posted @ 2006-07-25 10:17  谢多  阅读(451)  评论(0)    收藏  举报