使用DataTable动态绑定GridView

//绑定GridView
void ShowGrid()
        {
            DataTable newdt = "指定的数据源";

            gridSelectFile.AutoGenerateColumns = false;
            gridSelectFile.ShowHeader = true;
            gridSelectFile.DataKeyNames = new String[] { "Id" };
            DataControlFieldCollection dcfc = gridSelectFile.Columns;
            dcfc.Clear();
            BoundField bf;

            bf = new BoundField();
            bf.DataField = "Id";
            bf.Visible = false;
            dcfc.Add(bf);

            bf = new BoundField();
            bf.DataField = "FileName";
            bf.HeaderText = "文件名";
            bf.ItemStyle.Width = Unit.Parse("324px");
            dcfc.Add(bf);

            ButtonField opRow = new ButtonField();
            opRow.ButtonType = ButtonType.Button;
            opRow.AccessibleHeaderText = "DelRow";
            opRow.CommandName = "DelRow";
            opRow.CausesValidation = true;
            opRow.Text = "删除";
            opRow.ItemStyle.Width = Unit.Parse("40px");
            opRow.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            dcfc.Add(opRow);

            gridSelectFile.DataSource = newdt.DefaultView;
            gridSelectFile.DataBind();

         }

void gridSelectFile_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                (e.Row.Cells[2].Controls[0] as Button).Font.Size = FontUnit.Parse("9");
                (e.Row.Cells[2].Controls[0] as Button).BorderStyle = BorderStyle.Outset;
                (e.Row.Cells[2].Controls[0] as Button).BorderWidth = Unit.Parse("1px");
                (e.Row.Cells[2].Controls[0] as Button).Height = Unit.Parse("15px");
                Button btnDelete = (Button)e.Row.Cells[2].Controls[0];
                btnDelete.Attributes.Add("onclick", "javascript:return confirm('你确认要删除此记录吗?')");
            }
        }

void gridSelectFile_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //单击Grid中按钮时发生
            int selIndex = Convert.ToInt32(e.CommandArgument);

            if (e.CommandName == "DelRow")
            {
                try
                {
                    //从附件列表中移除此项
                    DataRow[] drs = newdt.Select("Id=" + gridSelectFile.DataKeys[selIndex].Value.ToString());
                    foreach (DataRow dr in drs)
                    {
                        dr.Delete();
                    }

                }
                catch (Exception err)
                {
                    ShowMessageBox("删除失败 \n" + err.Message);
                }
            }

            ShowGrid();
        }

转载于:https://www.cnblogs.com/catliu/archive/2007/02/26/657275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值