我有3个任务:
例如:在gridview中共有10行记录。如果用户单击第二行按钮,则必须获取整行详细信息,行的索引值,然后从第三行插入5行五行记录。
这是我的代码: Sample.aspx
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>
Sample.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BoundField bfield = new BoundField();
bfield.HeaderText = "Name";
bfield.DataField = "Name";
GridView1.Columns.Add(bfield);
TemplateField tfield = new TemplateField();
tfield.HeaderText = "Country";
GridView1.Columns.Add(tfield);
tfield = new TemplateField();
tfield.HeaderText = "Id";
GridView1.Columns.Add(tfield);
//BindGrid();
}
this.BindGrid();
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnRefresh_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtCountry = new TextBox();
txtCountry.ID = "txtCountry";
txtCountry.Text = (e.Row.DataItem as DataRowView).Row["Country"].ToString();
e.Row.Cells[1].Controls.Add(txtCountry);
Button lnkView = new Button();
lnkView.ID = "lnkView";
lnkView.Text = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[2].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
Button lnkView = (sender as Button);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[0].Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
}
最重要的是:我应该获取该行的索引并在两条记录之间插入记录。
答案 0 :(得分:0)
对于您的重复记录问题:GridView
控件上有一个名为AutoGenerateColumns
的属性。它默认为true
。
如果为true,则数据源中的所有列/字段/属性将自动显示为结果中的列。如果您随后添加了列,那么除了(和之后)自动生成的列之外,还会显示这些列。
这很容易解决:将AutoGenerateColumns
属性更改为false
:
<asp:GridView ID="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="false"></asp:GridView>
如果出现其他问题,请另外提出问题。