//绑定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();
}