日期:2014-05-18  浏览次数:20471 次

DataGrid添加行的问题 急
本人是初学者遇到如下问题:
一个按钮和一个DataGrid,DataGrid的数据源为空,单击按钮可在DataGrid添加一行,并且可以编辑内容,保存删除,应当怎样写

------解决方案--------------------

if (ds.tables[0].rows.count==0)
{
adddummydata(ds)
}


private void adddummyData(dataset ds)
{datatable dt =ds.tables[0];
datarow newrow=dt.newrow();
dt.rows.add(newrow);
}

------解决方案--------------------
<asp:DataGrid id= "DataGrid1 " runat= "server " BorderColor= "Aqua " AutoGenerateColumns= "False " Width= "376px "
Font-Size= "12px ">
<Columns>
<asp:BoundColumn DataField= "id " HeaderText= "ID "> </asp:BoundColumn>
<asp:BoundColumn DataField= "name " HeaderText= "NAME "> </asp:BoundColumn>
<asp:EditCommandColumn ButtonType= "LinkButton " UpdateText= "更新 " CancelText= "取消 " EditText= "编辑 "> </asp:EditCommandColumn>
<asp:ButtonColumn Text= "删除 " CommandName= "Delete "> </asp:ButtonColumn>
</Columns>
</asp:DataGrid>
<asp:Button id= "Button1 " runat= "server " Text= "Add Row "> </asp:Button>
=======================
page_load()
{
if(!this.IsPostBack)this.BindData();
}
private void BindData()
{
table = new DataTable( "myTable ");
table.Columns.Add( "id ");
table.Columns.Add( "name ");
DataRow row = table.NewRow();
row[0] = "1 ";
row[1] = "zhang san ";
table.Rows.Add(row);
this.DataGrid1.DataSource = table;
this.DataGrid1.DataBind();
}
private void Button1_Click(object sender, System.EventArgs e)
{
DataRow row = table.NewRow();
row[0] = " ";
row[1] = " ";
table.Rows.Add(row);
this.DataGrid1.EditItemIndex = table.Rows.Count-1;
this.DataGrid1.DataSource = table;
this.DataGrid1.DataBind();
}

private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex = e.Item.ItemIndex;
this.DataGrid1.DataSource = table;
this.DataGrid1.DataBind();
}

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

private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
table.Rows[e.Item.ItemIndex].Delete();
this.DataGrid1.DataSource = table;
this.DataGrid1.DataBind();
}

private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
table.Rows[e.Item.ItemIndex][0] = ((TextBox)e.Item.Cells[0].Controls[0]).Text;
table.Rows[e.Item.ItemIndex][1] = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
this.DataGrid1.EditItemIndex = -1;
this.DataGrid1.DataSource = table;
this.DataGrid1.DataBind();
}