2010-05-09 57 views
0

我想让用户能够从页脚行创建一个新的记录,我的事件处理程序似乎并没有工作......或者也许我在这一切都是错误的。尝试添加插入行到页脚在GridView ASP.net

插入按钮,我在GridView启用不工作要么...在http://aisched.engr.oregonstate.edu/admin/courses.aspx

这里签该网站是我在前面的代码背后:

public partial class admin_courses : System.Web.UI.Page 
{ 
public Table table; 
ListDictionary listValues = new ListDictionary(); 
TextBox textBox1 = new TextBox(); //Name 
TextBox textBox2 = new TextBox(); //CR 
TextBox textBox3 = new TextBox(); //CourseNum 
TextBox textBox4 = new TextBox(); //Dept 



protected void Page_Init() 
{ 

} 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer 

    textBox1.ID = "name"; 
    textBox1.Width = 250; 
    textBox2.ID = "credit_hours"; 
    textBox2.Width = 25; 
    textBox3.ID = "dept"; 
    textBox3.Width = 30; 
    textBox4.ID = "class"; 
    textBox4.Width = 25; 

    LinkButton add = new LinkButton(); 
    add.ID = "add"; 
    add.Text = "Add course"; 
    add.CommandName = "add"; 
    add.Click += new EventHandler(add_Click); 

    e.Row.Cells[1].Controls.Add(textBox1); 
    e.Row.Cells[2].Controls.Add(textBox2); 
    e.Row.Cells[3].Controls.Add(textBox3); 
    e.Row.Cells[4].Controls.Add(textBox4); 
    e.Row.Cells[5].Controls.Add(add); 

} 


public void add_Click(object sender, EventArgs e) 
{ 
    Response.Write("you Clicked Add Course!"); 

     if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) { 
      listValues.Add("name", textBox1.Text); 
      listValues.Add("credit_hours", textBox2.Text); 
      listValues.Add("dept", textBox4.Text); //For Visual 
      listValues.Add("class", textBox3.Text); 
     } 
     LinqDataSource1.Insert(listValues); 
     Response.Redirect("~/admin/courses.aspx"); 
} 

}

<%@ Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %> 

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server"> 
<ul id="main"> 
    <li><a href="overview.aspx">Overview</a></li> 
    <li><a href="users.aspx">Users</a></li> 
    <li class="current_page_item"><a href="courses.aspx">Courses</a></li> 
    <li><a href="programs.aspx">Programs</a></li> 
    <li><a href="sections.aspx">Sections</a></li> 
    <li><a href="import.aspx">Import</a></li> 
    <li><a href="logs.aspx">Logs</a></li> 
</ul> 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> 
<form id="Form1" runat="server"> 
<asp:ScriptManager ID="ScriptManager1" runat="server"> 
</asp:ScriptManager> 
<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
ContextTypeName="DataClassesDataContext" EnableDelete="True" 
EnableInsert="True" EnableUpdate="True" TableName="courses"> 
</asp:LinqDataSource> 
<h1><a>Courses</a></h1> 
<asp:UpdateProgress ID="UpdateProgress1" runat="server"> 
</asp:UpdateProgress> 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="course_id" DataSourceID="LinqDataSource1" 
    BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
    CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True" 
    OnRowDataBound="GridView1_RowDataBound" > 
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> 
<Columns> 
    <asp:BoundField DataField="course_id" HeaderText="ID" 
     ReadOnly="True" SortExpression="course_id" /> 
    <asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" /> 
    <asp:BoundField DataField="credit_hours" HeaderText="CR" 
     SortExpression="credit_hours" /> 
    <asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" /> 
    <asp:BoundField DataField="class" HeaderText="#" SortExpression="class" /> 
    <asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True" 
     ShowEditButton="True" ShowInsertButton="True"/> 
</Columns> 
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> 
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> 
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> 
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> 
</asp:GridView> 


<br /> 
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink> 
<br /> 

</form> 

</asp:Content> 
+0

你应该总是绑定的事件处理程序,即使你创建初始化按钮,然后在的RowDataBound – 2011-12-09 22:12:36

回答

1

我希望(或者至少我当然希望)有更好的方法来做到这一点,但试试这个:

<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" /> 
<h1> 
    <a> 
     Courses</a></h1> 
<asp:UpdateProgress ID="UpdateProgress1" runat="server"> 
</asp:UpdateProgress> 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id" 
    DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" 
    BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True" 
    ShowFooter="True"> 
    <Columns> 
     <asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id" 
      InsertVisible="False" /> 
     <asp:TemplateField HeaderText="name" SortExpression="name" > 
      <EditItemTemplate> 
       <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:TextBox ID="NameTextBox" runat="server" /> 
      </FooterTemplate> 

     </asp:TemplateField> 
     <asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours"> 
      <EditItemTemplate> 
       <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:TextBox ID="HoursTextBox" runat="server" /> 
      </FooterTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="dept" SortExpression="dept"> 
      <EditItemTemplate> 
       <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:TextBox ID="DeptTextBox" runat="server" /> 
      </FooterTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="class" SortExpression="class"> 
      <EditItemTemplate> 
       <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:TextBox ID="ClassTextBox" runat="server" /> 
      </FooterTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField ShowHeader="False"> 
      <EditItemTemplate> 
       <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" 
        Text="Update"></asp:LinkButton> 
       &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" 
        Text="Cancel"></asp:LinkButton> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" 
        Text="Edit"></asp:LinkButton> 
       &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" 
        Text="Delete"></asp:LinkButton> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" /> 
      </FooterTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     try 
     { 
      if (IsPostBack) 
      { 
       // We are in a Postback so check to see if the AddLinkButton was clicked 
       String eventTarget = Request.Form["__EVENTTARGET"].ToString(); 

       if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase)) 
       { 
        // We are adding a new row so build a ListDictionary with the controls from the footer row 
        ListDictionary values = new ListDictionary(); 

        values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text); 
        values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text); 
        values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text); 
        values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text); 

        // Pass the ListDictionary to the data source to send off to the database 
        LinqDataSource1.Insert(values); 

        // Refresh the grid so it shows the row we just added 
        GridView1.DataBind(); 
       } 
      } 
     } 
     catch (Exception) 
     { 

      throw; 
     } 
    } 

如果不手动编写代码来执行插入操作,我无法使其工作。处理Page_Load事件中的AddLinkBut​​ton_Click事件通过检查EventTarget隐藏字段来查看它是否以'addlinkbutton'结尾感觉是非常错误的,但它起作用。

+0

这真是棒极了菲尔添加按钮初始化 - 我如何设置列自动调整大小,所以他们没有比他们需要更宽/ – user326507 2010-05-11 17:06:37

+0

你几乎不能 - 你的选择是:在标记设置每个控件的宽度属性,或创建一个CSS类的宽度设置,然后设置th每个控件的CSSClass属性。对不起,但没有更好的方法来做到这一点! – PhilPursglove 2010-05-11 17:16:24

+0

好的,如果我想添加一个选定的行,我只是把下面的“删除”以下内容? 当我尝试处理后面的代码中的select时,我只有通过datagrid.row.cells [0]引用时才能访问“id”...但没有其他字段...? user326507 2010-05-11 21:12:49

0

可以从网格视图页脚添加的示例伪代码,最初数据保存在视图状态下,使用按钮单击事件来检查ViewState并将新数据插入到表中。

ASPX代码

 <asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound" 
    OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped"> 
    <EmptyDataTemplate> 
     No Data Found 
    </EmptyDataTemplate> 
    <Columns> 
     <asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%"> 
      <ItemTemplate> 
       <asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label> 
      </ItemTemplate> 

      <FooterTemplate> 
       <asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" /> 
      </FooterTemplate> 
     </asp:TemplateField> 

     <asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center"> 
      <ItemTemplate> 
       <asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' /> 
      </ItemTemplate> 

      <FooterTemplate> 
       <asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" /> 
      </FooterTemplate> 
     </asp:TemplateField> 

     <asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center"> 
      <ItemTemplate> 
       <asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' /> 
      </ItemTemplate> 

      <FooterTemplate> 
       <asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" /> 
      </FooterTemplate> 
      <ItemStyle Wrap="true" /> 
     </asp:TemplateField> 

     <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%"> 
      <ItemTemplate> 
       <asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20" 
        ToolTip="Edit"></asp:ImageButton> 
      </ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%"> 
      <ItemTemplate> 
       <asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20" 
        ToolTip="Delete"></asp:ImageButton> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20" 
        ToolTip="Add"></asp:ImageButton> 
      </FooterTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

服务器端代码

protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Footer) 
    { 
     List<TableOne> controlDetails = new List<TableOne>(); 
     controlDetails = dc.TableOne.Where(condition).ToList(); 
     controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" }); 
     DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList); 
     ddlDetails.DataSource = controlDetails; 
     ddlDetails.DataTextField = "Name"; 
     ddlDetails.DataValueField = "ID"; 
     ddlDetails.DataBind(); 
    } 
} 

protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    try 
    { 
     if (e.CommandName == "Delete") 
     { 
      GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer); 
      int RowIndex = gvr.RowIndex; 
      DataTable dtUserDetails = (DataTable)ViewState["gvUser"]; 
      DataRow dr = dtUserDetails.Rows[RowIndex]; 
      dr.Delete(); 
      gvUser.Rows[RowIndex].Visible = false; 
     } 
     else if (e.CommandName == "Edit") 
     { 
      DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails"); 
      CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne"); 
      CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo"); 

      GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer); 
      int RowIndex = gvr.RowIndex; 

      DataTable dtUserDetails = (DataTable)ViewState["gvUser"]; 
      DataRow dr = dtUserDetails.Rows[RowIndex]; 
      ddlDetails.SelectedValue = dr["DetailID"].ToString(); 
      CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]); 
      CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]); 
      dr.Delete(); 
     } 
     else if (e.CommandName == "Add") 
     { 
      DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails"); 
      CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne"); 
      CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo"); 

      if (ViewState["gvUser"] != null) 
      { 
       DataTable existingTable = (DataTable)ViewState["gvUser"]; 
       existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked); 
       ViewState["gvUser"] = existingTable; 
       gvUser.DataSource = existingTable; 
       gvUser.DataBind(); 
      } 
      else 
      { 
       DataTable dtUsers = new DataTable(); 
       dtUsers.Columns.Add("ID"); 
       dtUsers.Columns.Add("UserID"); 
       dtUsers.Columns.Add("DetailsID"); 
       dtUsers.Columns.Add("Details"); 
       dtUsers.Columns.Add("CheckOne"); 
       dtUsers.Columns.Add("CheckTwo"); 
       dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked); 
       ViewState["gvUser"] = dtUsers; 
       gvUser.DataSource = dtUsers; 
       gvUser.DataBind(); 
      } 
     } 
    } 
    catch (Exception) 
    { 

    } 
} 

//dummy function to avoid runtime grid error 
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 

} 
//dummy function to avoid runtime grid error 
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e) 
{ 

} 

protected void btnSave_Click(object sender, EventArgs e) 
{ 
    if (ViewState["gvUser"] != null) 
    { 
    TableOne userInfo = null; 
    List<TableOne> userDetails = new List<TableOne>(); 
    DataTable userSpecificDetails = (DataTable)ViewState["gvUser"]; 
    for (int i = 0; i < userSpecificDetails.Rows.Count; i++) 
    { 
     userInfo = new TableOne(); 
     userInfo.UserID = UserID; //supply value 
     foreach (DataColumn col in userSpecificDetails.Columns) 
     { 
      switch (col.ColumnName) 
      { 
       case "DetailsID": 
        userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]); 
        break; 
       case "CheckOne": 
        userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]); 
        break; 
       case "CheckTwo": 
        userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]); 
        break; 
      } 
     } 
     userDetails.Add(userInfo); 
    } 
    if (userDetails.Count > 0) 
    { 
     dc.TableOne.InsertAllOnSubmit(userDetails); 
     dc.SubmitChanges(); 
    } 
} 
}