asp.net 数据控件遍历

Gridview 数据访问
遍历
1、for遍历
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)//为gv的每一行增加js事件
{
   TextBox tb1 = (TextBox)GridView1.Rows[i].FindControl("time");
   tb1.Attributes.Add("onclick", "calendar();");//把js调用添加到每一行
   GridView1.Rows[i].Attributes.Add("OnMouseOver", "this.style.backgroundColor='#6699FF';this.style.color='#8C4510'");  
}
2、foreach遍历
 foreach (GridViewRow gr in GridView1 .Rows )
{
     TextBox tb1 = (TextBox)gr.FindControl("time");
}
Gridview 行索引
1、选中当前行(以linkbutton为例)
    protected void LinkButton2_Click(object sender, EventArgs e)//订单查看
    {
        LinkButton drp = sender as LinkButton; // 触发事件的 LinkButton
        GridViewRow row = drp.NamingContainer as GridViewRow; // GridView 当前行       
        int CurRow = row.RowIndex;
        LinkButton lk = (LinkButton)GridView4.Rows[CurRow].FindControl("LinkButton2");
        lk.Text = "kk";
    }
2、通过行事件取得控件所在行的行索引(以linkbutton为例)
    protected void GridView4_RowCommand(object sender, GridViewCommandEventArgs e)//行事件
    {
            GridViewRow gvrow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer); //获取被点击的linkButton所在的GridViewRow
            int index = gvrow.RowIndex; //获取到行索引 RowIndex
            //获取当前行的某列值
            //string userid=GridView1.Rows[index].Cells[列索引].Text.Trim();
             LinkButton  lk = (LinkButton)GridView4.Rows[index].FindControl("LinkButton2");
             lk.Text = "dd";
   }
Datalist数据访问
遍历
1.、for遍历
for (int i = 0; i < this.DataList1.Items.Count; i++)
{
   string value = ((Label)this.DataList1.Items[i].FindControl("price")).Text;
}
2、foreach遍历
foreach (DataListItem item in this.DataList1.Items)
{
     TextBox tb = (TextBox)item.FindControl("textbox1");
}
索引
1、选中当前行(以linkbutton为例)
protected void LinkButton1_Click(object sender, EventArgs e)
{
        LinkButton drp = sender as LinkButton; // 触发事件的 LinkButton
        DataListItem items = drp.NamingContainer as DataListItem;
        int CurRow = items.ItemIndex;
        LinkButton lk = (LinkButton)DataList1.Items[CurRow].FindControl("LinkButton1");
        lk.Text = "nihao";
}
Repeater数据访问
遍历
1、 for遍历
for (int i = 0; i < Repeater2.Items.Count;i++ )
{
     Literal ltr = Repeater2.Items[i].FindControl("Literal1");
}
2、 foreach遍历
foreach (RepeaterItem ri in Repeater2.Items)
{
 Literal ltr = (Literal)ri.FindControl("Literal1");
}
索引
1、 选中当前行(以linkbutton为例)
protected void LinkButton1_Click(object sender, EventArgs e)
{
Button bt = sender as Button;
        RepeaterItem ri = bt.NamingContainer as RepeaterItem;
        int cr = ri.ItemIndex;
        Label  idd = (Label )Repeater1.Items[cr].FindControl("idd");
}

你可能感兴趣的:(asp.net)