雖然標題是原創,但是其實主要的思想呢還是接見了曉風殘月的思路,今天在曉風殘月的博客上看到了如何利用GridView來實現雙擊進行編輯。我決定動手實現一下,由於還沒有實現雙擊進行更改操作,所以順便就把這個功能加了上去,希望對大家能有幫助,同時也謝謝曉風殘月。
效果圖如下:
![]()
前臺代碼
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand">
<FooterStyle BackColor="White" ForeColor="#000066" />
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="false" ButtonType="Link"/>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
![]()
<%...# Eval("customerid")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ID" runat ="server" Text='<%# Bind("customerid")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CompanyName">
<ItemTemplate>
![]()
<%...# Eval("CompanyName")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CName" runat ="server" Text='<%# Bind("CompanyName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContactName">
<ItemTemplate>
![]()
<%...# Eval("ContactName")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Name" runat ="server" Text='<%# Bind("ContactName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
![]()
<%...# Eval("Address")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Address" runat ="server" Text='<%# Bind("Address")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
</form>
後臺代碼
string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
![]()
...{
if (!IsPostBack)
![]()
...{
BindData();
}
}
![]()
![]()
private void BindData()
![]()
...{
![]()
SqlConnection MyCon = new SqlConnection(ConStr);
string QueryStr = "SELECT customerid,CompanyName,ContactName,Address FROM customers";
SqlDataAdapter Da = new SqlDataAdapter(QueryStr, MyCon);
DataSet Ds = new DataSet();
Da.Fill(Ds, "Customers");
GridView1.DataSource = Ds.Tables[0];
![]()
GridView1.DataKeyNames = new string[] ...{ "customerid" };
GridView1.DataBind();
![]()
}
![]()
protected override void Render(HtmlTextWriter writer)
![]()
...{
foreach (GridViewRow Row in GridView1.Rows)
![]()
...{
if (Row.RowType == DataControlRowType.DataRow)
![]()
...{
//雙擊進入編輯模式
Row.Attributes["ondblclick"] = ClientScript.GetPostBackEventReference(GridView1, "Edit$" + Row.RowIndex.ToString(), true);
Row.Attributes["style"] = "cursor:pointer";
Row.Attributes["title"] = "雙擊進入編輯";
if (Row.RowState == DataControlRowState.Edit)
![]()
...{
Row.Attributes.Remove("ondblclick");
Row.Attributes.Remove("style");
Row.Attributes["title"] = "編輯行";
for (Int32 i = 1; i < GridView1.Columns.Count; i++)
![]()
...{
((TextBox)Row.Cells[i].Controls[1]).Attributes.Add("onmouseover", "this.select()");
![]()
}
//雙擊更新
Row.Attributes["ondblclick"] = ClientScript.GetPostBackEventReference(GridView1, "Update$" + Row.RowIndex.ToString(), true);
![]()
}
//
for (int i = 1; i < Row.Cells.Count; i++)
![]()
...{
Page.ClientScript.RegisterForEventValidation(Row.UniqueID + "$ctl00", i.ToString());
}
}
}
base.Render(writer);
}
![]()
![]()
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
![]()
...{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
![]()
![]()
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
![]()
...{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
//防止非法的輸入,預防腳本攻擊
string CustomerId = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[1]).Text.ToString());
string CompanyName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[1]).Text.ToString());
string ContactName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[1]).Text.ToString());
string Address = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[1]).Text.ToString());
SqlConnection Con = new SqlConnection(ConStr);
string UpdateStr = "UPDATE customers SET companyname=@CompanyName,contactname=@ContactName,address=@Address WHERE customerid=@ID";
//插入數據的時候用參數來可以預防SQL注入攻擊,提高系統的安全性
SqlCommand UpdateCmd = new SqlCommand(UpdateStr,Con);
SqlParameter ParmID = new SqlParameter("@ID", SqlDbType.NVarChar,20);
ParmID.Value = ID;
SqlParameter ParmCName = new SqlParameter("@CompanyName", SqlDbType.NVarChar, 20);
ParmCName.Value = CompanyName;
SqlParameter ParmName = new SqlParameter("@ContactName",SqlDbType.NVarChar,20);
ParmName.Value = ContactName;
SqlParameter ParmAddr = new SqlParameter("@Address",SqlDbType.NVarChar,20);
ParmAddr.Value = Address;
try
![]()
...{
UpdateCmd.Parameters.Add(ParmCName);
UpdateCmd.Parameters.Add(ParmName);
UpdateCmd.Parameters.Add(ParmAddr);
UpdateCmd.Parameters.Add(ParmID);
Con.Open();
UpdateCmd.ExecuteNonQuery();
Con.Close();
}
catch
![]()
...{
ShowMessage("輸入格式不正確,請檢查");
}
finally
![]()
...{
Con.Close();
GridView1.EditIndex = -1;
BindData();
}
}
![]()
private void ShowMessage(string Message)
![]()
...{
Literal TxtMsg = new Literal();
TxtMsg.Text = "<script>alert('" + Message + "')</script>";
Page.Controls.Add(TxtMsg);
}
![]()
![]()
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
![]()
...{
![]()
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
![]()
...{
GridView ControlGridView = (GridView)sender;
if (e.CommandName == "SingleClick")
![]()
...{
int RowIndex = int.Parse(e.CommandArgument.ToString());
int ColIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);
Response.Write("<script>alert('你點擊了第"+(RowIndex+1)+"行的第"+(ColIndex)+"列');</script>");
![]()
}
}
}