后台程序:
public partial class tw2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.createdb();
}
}
private void createdb()
{
SqlConnection cn = new SqlConnection("server=.;database=zhang;uid=sa;pwd=410"); //(Data Source =服务器;Initial Catalog=数据库;Integrated Security=True")本地用户登录
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = new SqlCommand("select * from chang", cn);
DataSet ds = new DataSet();
adp.Fill(ds, "chang");
this.GridView1.DataKeyNames = new string[] { "changid" }; //定义主键
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.GridView1.DataBind();
cn.Close(); }
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) //取消按钮
{
GridView1.EditIndex = -1;
this.createdb();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) //编辑按钮
{
GridView1.EditIndex = e.NewEditIndex;
this.createdb();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) //选择按钮
{
int id = Convert.ToInt32(e.CommandArgument); //取行索引号
string txt = GridView1.DataKeys[id].Value.ToString(); //取主键的值
Response.Write(txt);
// this.createdb(); }
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) //删除按钮
{
//在删除事件中获取绑定列的值 GridView1.Rows[e.RowIndex].Cells[1].Text.ToString();
SqlConnection cn = new SqlConnection("server=.;database=zhang;uid=sa;pwd=410");
cn.Open();
SqlCommand cm=new SqlCommand("delete from chang where changid=" +GridView1.DataKeys[e.RowIndex].Value,cn); //e.RowIndex取本行索引号,
cm.ExecuteNonQuery();
cn.Close();
GridView1.EditIndex = -1;
this.createdb(); }
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) //更新按钮
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox box = (TextBox)row.Cells[2].Controls[0];
Response.Write(box.Text);
try
{
SqlConnection cn = new SqlConnection("server=.;database=zhang;uid=sa;pwd=410");
cn.Open();
SqlCommand cm = new SqlCommand("update chang set chang1='" + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',chang2='" + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where changid=" + GridView1.DataKeys[e.RowIndex].Value, cn); //列的编号是从1,这里更新的是第二列和第三列所以cell[2],cell[3],而行的索引是从0开始的
cm.ExecuteNonQuery();
GridView1.EditIndex = -1;
this.createdb();
cn.Close();
//在更新事件中获取其他绑定列的值
// GridView1.Rows[e.RowIndex].Cells[9].Text.ToString();
//由于隐藏列不能获取其值,可以用以下方法:
//1.先定义个隐藏样式
<style type="text/css">
.hidden { display:none;}
</style>
2.在隐藏列的HTML标记里引用这个样式,代码如下:
<asp:BoundField DataField="num" ReadOnly="True">
<HeaderStyle CssClass="hidden" />
<ItemStyle CssClass="hidden" />
</asp:BoundField>
//这样就可以获取隐藏列的值了,比如修改出库数量的时候要先判断库存等。
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
}
}