花了一天的时间弄清楚了formView里边的那些事件是怎么回事。网上几乎没有单独使用formview的教程,而且很多教程写的都不是很清楚。自己摸索了一天把这个空间算是有点弄明白了,我也只是个小白,刚入行没多少时间,做程序员还是要考虑好,写代码一不小心就写成体力活了。
废话不多说切入正题:
首先拖一个formview控件到页面上,然后编辑好你所需要的模板
<asp:FormView ID="FormView1" runat="server" OnItemCreated="FormView1_ItemCreated" OnModeChanging="FormView1_ModeChanging" OnItemUpdating="FormView1_ItemUpdating"> <EditItemTemplate> <P><span>标题:</span><asp:TextBox id="txtTitle" Text='<%#Bind("Title") %>' runat="server" /></P> <div> <asp:TextBox id="txtContent" Text='<%#Bind("content") %>' runat="server" CssClass="xheditor" TextMode="MultiLine" Width="560" Height="250px" /> </div> <asp:Button ID="Button1" runat="server" CommandName="Update" Text="提交更新" /> <asp:Button ID="Button2" runat="server" CommandName="Cancel" Text="取消编辑" /> </EditItemTemplate> <InsertItemTemplate> <P><span>标题:</span><asp:TextBox id="txtTitle" Text='' runat="server" /></P> <div> <asp:TextBox id="txtContent" Text='' runat="server" CssClass="xheditor" TextMode="MultiLine" Width="560" Height="250" /> </div> <asp:Button ID="Button1" runat="server" CommandName="Insert" Text="新建" /> <asp:Button ID="Button2" runat="server" CommandName="Cancel" Text="取消" /> </InsertItemTemplate> <ItemTemplate> <p><span>标题:</span><%#Eval("title") %></p> <div> <%#Eval("content") %> </div> <asp:Button id="btnSub" Text="" runat="server" CommandName="Edit"/> </ItemTemplate> </asp:FormView>
这个文本编辑器是网上找的一个开源的编辑器需要的话文末会提供链接。
使用formview在网页加载的时候绑定数据代码如下 :
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class admin_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { NewMethod(); } } private void NewMethod() { MySql connect = new MySql(); string sql = "select * from intro"; DataSet ds = connect.SelectSqlReturnDataSet(sql); FormView1.DataSource = ds; FormView1.DataBind(); } /// <summary> /// 判断数据集是否为空 /// </summary> /// <param name="dataSet"></param> /// <returns></returns> public bool IsEmpty(DataSet dataSet) { foreach (DataTable table in dataSet.Tables) if (table.Rows.Count != 0) return false; return true; } protected void FormView1_ItemCreated(object sender, EventArgs e) { if (FormView1.CurrentMode == FormViewMode.ReadOnly) { MySql connect = new MySql(); string sql = "select * from intro"; DataSet ds = connect.SelectSqlReturnDataSet(sql); Button btnSub = ((Button)FormView1.Row.FindControl("btnSub")); if (IsEmpty(ds)) { btnSub.CommandName = "New"; btnSub.Text = "新建"; } else { btnSub.CommandName = "Edit"; btnSub.Text = "编辑"; } } } protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e) { FormView1.ChangeMode((FormViewMode)e.NewMode); NewMethod(); } protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) { MySql connect = new MySql(); string sql = "update intro set title=@title,content=@content,username=(select ID from account where username = @username)"; SqlParameter p1 = new SqlParameter("@title", SqlDbType.VarChar) { Value = e.NewValues["Title"].ToString() }; SqlParameter p2 = new SqlParameter("@content", SqlDbType.Text) { Value = e.NewValues["content"].ToString() }; SqlParameter p3 = new SqlParameter("@username", SqlDbType.VarChar) { Value = Session["user"].ToString() }; int o = connect.ExecuteSqlReturnInt(sql, p1, p2, p3); if (o>0) { Label message = new Label(); message.Text = "更新成功"; Page.Controls.Add(message); FormView1.ChangeMode(FormViewMode.ReadOnly); NewMethod(); } else { Label message = new Label(); message.Text = "更新失败"; Page.Controls.Add(message); } } }
public class MySql { #region 字段 public static readonly string Connect = System.Configuration.ConfigurationManager.ConnectionStrings["Mysql"].ConnectionString.ToString(); #endregion /// <summary> /// 基于SQL命令或基于存储过程 实现数据库操作 /// </summary> /// <param name="sql">insert,update,delete相关命令</param> /// <returns>受影响的行数 int </returns> public int ExecuteSqlReturnInt(string sql, params SqlParameter[] pars) { SqlConnection conn = new SqlConnection(MySql.Connect); try { SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken) { conn.Open(); } #region 给命令对象添加参数 if (pars != null || pars.Length > 0) { foreach (SqlParameter p in pars) { cmd.Parameters.Add(p); } } #endregion int count = cmd.ExecuteNonQuery(); return count; } catch (System.Exception ex) { return 0; } finally { conn.Close(); } } /// <summary> /// 基于SQL实现查询,返回数据集合 /// </summary> /// <param name="sql">select * from ~~</param> /// <returns>dataset</returns> public DataSet SelectSqlReturnDataSet(string sql) { SqlConnection conn = new SqlConnection(MySql.Connect); SqlDataAdapter sdr = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sdr.Fill(ds); return ds; } /// <summary> /// 基于SQL实现参数化查询,返回数据集合 /// </summary> /// <param name="sql">select * from ~~</param> /// <returns>dataset</returns> public DataSet SelectSqlReturnDataSet(string sql, params SqlParameter[] pars) { SqlConnection conn = new SqlConnection(MySql.Connect); SqlDataAdapter sdr = new SqlDataAdapter(sql, conn); if (pars != null && pars.Length > 0 ) { foreach (SqlParameter p in pars) { sdr.SelectCommand.Parameters.Add(p); } } DataSet ds = new DataSet(); sdr.Fill(ds); return ds; } /// <summary> /// 返回数据阅读器对象 /// </summary> /// <param name="sql">"select * from tbUser where userid=123"</param> /// <returns>SqlDataReader</returns> public SqlDataReader SelectSqlReturnDataReader(string sql) { SqlConnection conn = new SqlConnection(MySql.Connect); SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken) { conn.Open(); } SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); return dr; } /// <summary> /// 返回数据阅读器对象 /// </summary> /// <param name="sql">"select * from tbUser where userid=@userid"</param> /// <returns>SqlDataReader</returns> public SqlDataReader SelectSqlReturnDataReader(string sql,params SqlParameter[] pars) { SqlConnection conn = new SqlConnection(MySql.Connect); SqlCommand cmd = new SqlCommand(sql, conn); if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken) { conn.Open(); } if (pars != null && pars.Length >0) { foreach (SqlParameter p in pars) { cmd.Parameters.Add(p); } } SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); return dr; } }
formview可以自由定义模板模板中的控件的CommandName属性
这些东西很官方我不知道怎么写,网上查的到的东西我就不想多写了,直接在点击CommandName = ”Edit“按钮的时候会调用ModeChanging事件,那么ModeChanging事件一定是用来改变控件状态的。ModeChanging事件有两个参数(object sender, FormViewModeEventArgs e)
object sender 发出事件的对象
System.EventArgs e 对象中的数据
如果是按钮button的话,那sender就是那个button,
e是事件参数,在某些事件里,e用处不大,比如在MouseEventArgs的Mouse事件中,可以看到e包括mouse的坐标值等,以供你的程序使用。
那么E中就一定包涵编辑改变的状态。重点强调的是,状态改变后一定要重新绑定数据否者是不会切换到改变的状态的。代码如下:
protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e) { FormView1.ChangeMode((FormViewMode)e.NewMode); //必须重新绑定,否者不会切换到当前改变的状态... MySql connect = new MySql(); string sql = "select * from intro"; DataSet ds = connect.SelectSqlReturnDataSet(sql); FormView1.DataSource = ds; FormView1.DataBind(); }
如果手动绑定数据没有关联这个事件就会报错。
另外一个事件是更新事件ItemUpdating这个事件是编辑状态点击CommandName=”Update” 的按钮是产生的事件。用来执行更新数据库的操作。
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) { MySql connect = new MySql(); string sql = "update intro set title=@title,content=@content,username=(select ID from account where username = @username)"; SqlParameter p1 = new SqlParameter("@title", SqlDbType.VarChar) { Value = e.NewValues["Title"].ToString() }; SqlParameter p2 = new SqlParameter("@content", SqlDbType.Text) { Value = e.NewValues["content"].ToString() }; SqlParameter p3 = new SqlParameter("@username", SqlDbType.VarChar) { Value = Session["user"].ToString() }; int o = connect.ExecuteSqlReturnInt(sql, p1, p2, p3); if (o>0) { Label message = new Label(); message.Text = "更新成功"; Page.Controls.Add(message); FormView1.ChangeMode(FormViewMode.ReadOnly); NewMethod(); } else { Label message = new Label(); message.Text = "更新失败"; Page.Controls.Add(message); } }
插入也是一样要写相应的事件代码,和数据库操作代码。
省下的就是怎么查找FormView控件里的控件了。微软为我们提供了一个FindControl方法,但是这个方法只在ItemCreated事件里才有效,我也不知道这话该怎么说,反正就是你在Page_load里边写的话会报错,提示未将对象引用到实例。
下边是我写的一个例子:
protected void FormView1_ItemCreated(object sender, EventArgs e) { if (FormView1.CurrentMode == FormViewMode.ReadOnly) { MySql connect = new MySql(); string sql = "select * from intro"; DataSet ds = connect.SelectSqlReturnDataSet(sql); Button btnSub = ((Button)FormView1.Row.FindControl("btnSub")); if (IsEmpty(ds)) { btnSub.CommandName = "New"; btnSub.Text = "新建"; } else { btnSub.CommandName = "Edit"; btnSub.Text = "编辑"; } } }
关于这个控件就完了。我不太会写博文,但是我相信代码肯定可以理解。不懂的欢迎提问,欢迎大神指正。
附上开源的编辑器:http://xheditor.com/