locked
How to maintain state of web controls in gridview when adding new row dynamically RRS feed

  • Question

  • User-718146471 posted

    Hello folks, I'm trying to get around a rather annoying problem. To add a row dynamically, it requires me to do a page postback which will wipe out anything I have entered on my gridview form. I suspect I am going to need to use session state to maintain the objects, however I do not have a huge amount of experience working with it so guidance is appreciated! Now, onto the code which I will include UI and C# code.

    UI:

    <%@ Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="WASAuditSystem.GridViewDemo" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
        <div>
                <style type="text/css">
            .auto-style1 {
                width: 90%;
            }
            .auto-style2 {
                width: 87px;
            }
            .auto-style3 {
                width: 89px;
            }
            .auto-style4 {
                width: 91px;
            }
            .auto-style5 {
                width: 93px;
            }
            .auto-style6 {
                width: 355px;
            }
            .auto-style7 {
                width: 114%;
            }
            .item {white-space: nowrap;display:inline  }
        </style>
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <table class="auto-style7">
            <tr>
                <td class="auto-style6" style="vertical-align: top; text-wrap:none;">&nbsp;</td><td class="auto-style4" style="vertical-align: top;">&nbsp;</td>
                <td class="auto-style2" style="vertical-align: top;">
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style6" style="vertical-align: top; text-wrap:none;">*Auditor</td><td class="auto-style4" style="vertical-align: top;">
                <asp:DropDownList ID="ddlAuditor" runat="server">
                    <asp:ListItem Selected="True">-- SELECT --</asp:ListItem>
                    <asp:ListItem Value="xxxxxxxxxxxxxxxxxxxx">xxxxxxxxxxxxxxxxxxxx</asp:ListItem>
                    <asp:ListItem Value="xxxxxxxxxxxxxxxxxxxx">xxxxxxxxxxxxxxxxxxxx</asp:ListItem>
                    <asp:ListItem Value="xxxxxxxxxxxxxxxxxxxx">xxxxxxxxxxxxxxxxxxxx</asp:ListItem>
                    <asp:ListItem Value="xxxxxxxxxxxxxxxxxxxx">xxxxxxxxxxxxxxxxxxxx</asp:ListItem>
                    <asp:ListItem Value="xxxxxxxxxxxxxxxxxxxx">xxxxxxxxxxxxxxxxxxxx</asp:ListItem>
                </asp:DropDownList>
                <br />
                </td>
                <td class="auto-style2" rowspan="3" style="vertical-align: top;">
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style6" style="vertical-align: top; text-wrap:none;">*App Name:</td><td class="auto-style4" style="vertical-align: top;"><asp:TextBox ID="txtAppName" runat="server" Width="491px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style6" style="vertical-align: top; text-wrap:none;">*Dev Email:</td><td class="auto-style5" style="vertical-align: top;"><asp:TextBox ID="txtDevEmail" runat="server" Width="490px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style6" style="vertical-align:top; text-wrap:none;">CC:<br />
                    (use ; for addresses)</td><td class="auto-style5" style="vertical-align: top;">
                    <asp:TextBox ID="txtCCDevs" runat="server" TextMode="MultiLine" Rows="4" Width="486px"></asp:TextBox></td>
            </tr>
                <tr>
                <td class="auto-style6" style="vertical-align: top; text-wrap:none; color: red;"><strong>* Required </strong></td><td class="auto-style5" style="vertical-align: top;">
                    <asp:RequiredFieldValidator ID="rfAuditor" runat="server" ControlToValidate="ddlAuditor" ErrorMessage="&lt;br /&gt;Choose the auditor name" Font-Bold="True" ForeColor="Red" InitialValue="-- SELECT --"></asp:RequiredFieldValidator>
                <asp:RequiredFieldValidator ID="rfvAppName" runat="server" ControlToValidate="txtAppName" ErrorMessage="<br />Application name is required" Font-Bold="True" ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>            
                <asp:RequiredFieldValidator ID="rfvDevEmail" runat="server" ControlToValidate="txtDevEmail" ErrorMessage="<br />Developer Email Address required" Font-Bold="True" ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>
                <div id="GVErrors" />
                <asp:Label ID="lblBothErr" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>            
                <asp:Label ID="lblCountErr" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>            
                <asp:Label ID="lblTypeErr" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
                </td>
                <td class="auto-style2" style="vertical-align: top;"></td>
            </tr>
            <tr>
                <td class="auto-style3" style="vertical-align: top; text-wrap:none;" colspan="3">&nbsp;
                <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="auto-style3" style="vertical-align: top; text-wrap:none;" colspan="3">
                <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Send Message" Visible="false" />
                </td>
            </tr>
        </table>
            <asp:Panel runat="server" ID="pnlPlaceHolder">
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%">
                <Columns>
                    <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:LinkButton ID="addCmd" runat="server" CausesValidation="false" CommandName="add" Text="Add" CommandArgument='<%# Bind("VulnerabilityToSystemId") %>' Visible='<%# Eval("TempId").ToString() == "00000000-0000-0000-0000-000000000000" ? true : false  %>' OnCommand="addCmd_Command"><img src="images/insert.jpg" width="25px" height="25px" border="0" /></asp:LinkButton><asp:LinkButton ID="remCmd" runat="server" CausesValidation="false" CommandName="delete" Text="Remove" CommandArgument='<%# Bind("TempId") %>' Visible ='<%# Eval("TempId").ToString() == "00000000-0000-0000-0000-000000000000" ? false : true  %>' OnCommand="removeCmd_Command"><img src="images/delete.jpg" width="25px" height="25px" border="0" /></asp:LinkButton><asp:HiddenField ID="VulnerabilityToSystemId" runat="server" Value='<%# Bind("VulnerabilityToSystemId") %>' /><asp:HiddenField ID="VulnerabilityId" runat="server" Value='<%# Bind("VulnerabilityId") %>'  /><asp:HiddenField ID="TempId" runat="server" Value='<%# Bind("TempId") %>'  />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name" ItemStyle-CssClass="label">
                        <ItemTemplate>
                            <div class="item"><asp:CheckBox ID="cbVulnName" runat="server" Value='<%# Eval("Vuln_Name") %>' />&nbsp;&nbsp;<asp:Label ID="lblVulnName" runat="server" Text='<%# Eval("Vuln_Name") %>'></asp:Label></div>
                        </ItemTemplate>
                        <ItemStyle Font-Size="X-Small" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Type">
                        <ItemTemplate>
                            <asp:DropDownList ID="ddlType" runat="server" Width="140px">
                                <asp:ListItem Selected="True" Value="--SELECT--">--SELECT--</asp:ListItem>
                                <asp:ListItem>Suspicious</asp:ListItem>
                                <asp:ListItem>Exploitable</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                        <ControlStyle Font-Size="X-Small" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Count">
                        <ItemTemplate>
                            <asp:TextBox ID="txtCount" runat="server" Width="50px"></asp:TextBox>
                        </ItemTemplate>
                        <ItemStyle Font-Size="X-Small" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Reference">
                        <ItemTemplate>
                            <asp:HyperLink ID="hlComments" runat="server" Height="25px" ImageHeight="25px" ImageUrl="~/images/www.png" ImageWidth="25px" NavigateUrl='<%# Eval("Vuln_Reference") %>' Width="25px"></asp:HyperLink>
                            <asp:Label Visible="false" ID="lblComments" runat="server" Text='<%# Eval("Vuln_Reference") %>'></asp:Label>
                        </ItemTemplate>
                        <ItemStyle Font-Size="X-Small" />
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
                <asp:Button ID="btnPrepare" runat="server" OnClick="btnPrepare_Click" Text="Prepare Message" />
                </asp:Panel>
    </asp:Content>

    cs:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WASAuditSystem
    {
        public partial class GridViewDemo : System.Web.UI.Page
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
            //Mock repo
            private List<VulnerabilityToSystem> Vulnerabilities
            {
                get
                {
                    if (ViewState["VulnerabilityToSystemList"] != null)
                    {
                        return ((List<VulnerabilityToSystem>)ViewState["VulnerabilityToSystemList"]).
                            OrderBy(m => m.VulnerabilityId).
                            ThenBy(m => m.SortOrder).ToList();
                    }
                    return GetVulnerabilities().OrderBy(m => m.VulnerabilityId).ThenBy(m => m.SortOrder).ToList();
                }
                set
                {
                    ViewState["VulnerabilityToSystemList"] = value;
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    Vulnerabilities = GetVulnerabilities();
                    BindGrid();
                }
    
            }
    
            private void BindGrid()
            {
                GridView1.DataSource = Vulnerabilities;
                GridView1.DataBind();
            }
    
            //Command button click handler
            protected void addCmd_Command(object sender, CommandEventArgs e)
            {
                int id = 0;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (int.TryParse(e.CommandArgument.ToString(), out id))
                    {
                        AddDuplicateRecordById(id);
                        BindGrid();
                    }
                }
            }
    
            protected void removeCmd_Command(object sender, CommandEventArgs e)
            {
                Guid id;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (Guid.TryParse(e.CommandArgument.ToString(), out id))
                    {
                        RemoveRecordByGuid(id);
                        BindGrid();
                    }
                }
            }
    
            private void RemoveRecordByGuid(Guid id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.TempId == id
                                              select d).First();
                repo.Remove(dup);
                Vulnerabilities = repo;
            }
    
            //Update Repo
            private void AddDuplicateRecordById(int id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
    
                //Create a copy
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.VulnerabilityToSystemId == id
                                              select new VulnerabilityToSystem()
                                              {
                                                  VulnerabilityToSystemId = 0,
                                                  VulnerabilityId = d.VulnerabilityId,
                                                  TempId = Guid.NewGuid(),
                                                  Vuln_Name=d.Vuln_Name,
                                                  type = d.type,
                                                  count = d.count,
                                                  Vuln_Reference = d.Vuln_Reference,
                                                  SortOrder = d.SortOrder + 1,
                                              }).FirstOrDefault();
                //Persist the Update
                repo.Add(dup);
                Vulnerabilities = repo;
            }
    
            //Mock data retrieval 
            protected List<VulnerabilityToSystem> GetVulnerabilities()
            {
                List<VulnerabilityToSystem> results = new List<VulnerabilityToSystem>();
                int i = 0;
                string SQLQuery = "SELECT Vuln_Name, Vuln_Reference FROM Vulnerabilities";
                SqlCommand cmd = new SqlCommand(SQLQuery, conn);
                conn.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = i, VulnerabilityId = i, Vuln_Name = rdr.GetValue(0).ToString(), count = "0", type = "-- SELECT --", Vuln_Reference = rdr.GetValue(1).ToString() });
                    i++;
                }
                return results;
            }
    
            protected void btnPrepare_Click(object sender, EventArgs e)
            {            
                Label1.Text = string.Empty;
                CheckBox tempC;
                Label tempCName;
                DropDownList ddlC;
                TextBox txtC;
                Label t1;
                int index = 1;
    
                Label1.Text += String.Format("<table style='border-spacing:2px; spacing:10px; padding:10px; border:solid;' width='100%'><tr style='background-color:#3399FF; text-transform: uppercase; color: white; font-weight: bolder;'><td>Name</td><td>Risk Level</td><td>Count</td><td>Reference</td></tr>");
                string vulnBoth = string.Empty, vulncount = string.Empty, vulntype = string.Empty;
                try
                {
                    foreach (GridViewRow row in GridView1.Rows)
                    {
                        tempC = (CheckBox)row.FindControl("cbVulnName");
                        if ((row.RowType == DataControlRowType.DataRow) && (tempC.Checked))
                        {
                            tempCName = (Label)row.FindControl("lblVulnName");
                            ddlC = (DropDownList)row.FindControl("ddlType");
                            t1 = (Label)row.FindControl("lblComments");
                            txtC = (TextBox)row.FindControl("txtCount");
                            if (t1.Text == null)
                            {
                                t1.Text = string.Empty;
                            }
                            if (index % 2 == 0)
                            {
                                Label1.Text += String.Format("<tr style='background-color:#CCEEFF;'>");
                                Label1.Text += String.Format("<td>{0}</td>", tempCName.Text);
                                Label1.Text += String.Format("<td>{0}</td>", ddlC.SelectedValue);
                                Label1.Text += String.Format("<td>{0}</td>", txtC.Text);
                                Label1.Text += String.Format("<td><a href={0}>Reference</a></td></tr>", t1.Text);
                                index++;
                            }
                            else
                            {
                                Label1.Text += String.Format("<tr style='background-color:#FFFFFF;'>");
                                Label1.Text += String.Format("<td>{0}</td>", tempCName.Text);
                                Label1.Text += String.Format("<td>{0}</td>", ddlC.SelectedValue);
                                Label1.Text += String.Format("<td>{0}</td>", txtC.Text);
                                Label1.Text += String.Format("<td><a href={0}>Reference</a></td></tr>", t1.Text);
                                index++;
                            }
                            if (tempC.Checked)
                            {
                                if ((txtC.Text.ToString() == string.Empty) & (ddlC.SelectedIndex == 0))
                                {
                                    vulnBoth = vulnBoth + "<br />You selected " + tempCName.Text.ToString() + " however you forgot to enter the count and select the vulnerability.";
                                }
                                else if (txtC.Text.ToString() == string.Empty)
                                {
                                    vulncount = vulncount + "<br />You selected " + tempCName.Text.ToString() + " however you forgot to enter the count.";
                                }
                                else if (ddlC.SelectedIndex == 0)
                                {
                                    vulntype = vulntype + "<br />You selected " + tempCName.Text.ToString() + " however you forgot to select the vulnerability type.";
                                }
                                lblBothErr.Text = vulnBoth.ToString();
                                lblCountErr.Text = vulncount.ToString();
                                lblTypeErr.Text = vulntype.ToString();
                            }
                        }
                        //ScriptManager.RegisterStartupScript(Page, typeof(Page), "GVErrors", "setTimeout(GVErrors, 1);", true);
                    }
                    try
                    {
                        if (rfAuditor.IsValid == true)
                        {
                            rfAuditor.Visible = false;
                        }
                        else
                        {
                            rfAuditor.Visible = true;
                            SetFocus(rfAuditor);
                        }
                        if (rfvAppName.IsValid == true)
                        {
                            rfvAppName.Visible = false;
                        }
                        else
                        {
                            rfvAppName.Visible = true;
                            SetFocus(rfvAppName);
                        }
                        if (rfvDevEmail.IsValid == true)
                        {
                            rfvDevEmail.Visible = false;
                        }
                        else
                        {
                            rfvDevEmail.Visible = true;
                            SetFocus(rfvDevEmail);
                        }
                    }
                    catch (Exception ex)
                    {
    
                    }
                    Label1.Text += String.Format("</table>");
                    btnSubmit.Visible = true;
                    if ((rfvDevEmail.IsValid = false) | (rfvAppName.IsValid = false) | (rfAuditor.IsValid = false) | (lblBothErr.Text != string.Empty) | (lblTypeErr.Text != string.Empty) | (lblCountErr.Text != string.Empty))
                    {
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnSubmit.Visible = true;
                    }
                }
                catch (Exception ex)
                {
    
                }
            }
    
            protected void btnSubmit_Click(object sender, EventArgs e)
            {
                string htmlBody = "Hello, I have audited " + txtAppName.Text.ToString() + ".<br><br>We have found the following issues. Please reply in SSC with your comments/fixes.<br><br>" + Label1.Text.ToString();
                htmlBody = htmlBody + "<br><br>Please let me know if you have any questions.<br><br>";
                string fromAddr = ddlAuditor.SelectedValue.ToString();
                string ccAddr = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
                string ccMulti = txtCCDevs.Text.ToString();
                string toAddr = txtDevEmail.Text.ToString();
                string Subject = "Application Evaluation: " + txtAppName.Text.ToString();
    
                try
                {
                    smtpHelper.SendMailMessage(fromAddr.ToString(), toAddr.ToString(), ccAddr.ToString(), txtCCDevs.Text.ToString(), Subject.ToString(), htmlBody.ToString());
                    ClearTextBoxes(Page);
                    Label1.Text = string.Empty;
                    btnSubmit.Visible = false;
                    GridView1.DataSource = Vulnerabilities;
                    GridView1.DataBind();
                    Response.Write("Successfully Sent.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.ToString());
                }
    
            }
    
            protected void ClearTextBoxes(Control p1)
            {
                foreach (Control ctrl in p1.Controls)
                {
    
                    if (ctrl is TextBox)
                    {
                        TextBox t = ctrl as TextBox;
    
                        if (t != null)
                        {
                            t.Text = String.Empty;
                        }
                    }
                    if (ctrl is CheckBox)
                    {
                        CheckBox cb = ctrl as CheckBox;
    
                        if (cb != null)
                        {
                            cb.Checked = false;
                        }
                    }
                    else
                    {
                        if (ctrl.Controls.Count > 0)
                        {
                            ClearTextBoxes(ctrl);
                        }
                    }
                }
            }
        }
        //Model
        [Serializable()]
        public class VulnerabilityToSystem
        {
            public int VulnerabilityToSystemId { get; set; }
            public int VulnerabilityId { get; set; }
            public Guid TempId { get; set; }
            public string Vuln_Name { get; set; }
            public string count { get; set; }
            public string type { get; set; }
            public int SortOrder { get; set; }
            public string Vuln_Reference { get; set; }
        }
    }

    Wednesday, January 13, 2016 3:59 PM

Answers

  • User475983607 posted

    Hello folks, I'm trying to get around a rather annoying problem. To add a row dynamically, it requires me to do a page postback which will wipe out anything I have entered on my gridview form. I suspect I am going to need to use session state to maintain the objects, however I do not have a huge amount of experience working with it so guidance is appreciated! Now, onto the code which I will include UI and C# code.

    The controls are data bound not dynamic so that makes this a little easier.  The tough part is dealing with possible multiple record updates on each post since the grid contains input elements on every row.  

    Be forewarned I had a few beers after work with the boys so you'll need to double check my work; int.Parse and Guid.Parse can be problematic.  

    Anyway, I added a dropdown that persists after clicking the add or remove buttons.  The trick is parsing the GridView early in the page life cycle to grab the submitted values and update the ViewState data store.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="TestingWeb.GridViewDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:TemplateField AccessibleHeaderText="Add" HeaderText="Add" ShowHeader="False">
                        <ItemTemplate>
                            <asp:LinkButton ID="addCmd" 
                                runat="server" 
                                CausesValidation="false" 
                                CommandName="add" 
                                Text="Add" 
                                CommandArgument='<%# Bind("VulnerabilityToSystemId") %>' 
                                OnCommand="addCmd_Command"></asp:LinkButton>
                            <asp:LinkButton ID="removeCmd" 
                                runat="server" 
                                CausesValidation="false" 
                                CommandName="delete" 
                                Text="Remove" 
                                CommandArgument='<%# Bind("TempId") %>' 
                                Visible ='<%# Eval("TempId").ToString() == "00000000-0000-0000-0000-000000000000" ? false : true  %>' 
                                OnCommand="removeCmd_Command"></asp:LinkButton>
                            <asp:HiddenField ID="VulnerabilityToSystemId" runat="server" Value='<%# Bind("VulnerabilityToSystemId") %>' />
                            <asp:HiddenField ID="VulnerabilityId" runat="server" Value='<%# Bind("VulnerabilityId") %>'  />
                            <asp:HiddenField ID="SystemId" runat="server" Value='<%# Bind("SystemId") %>'  />
                            <asp:HiddenField ID="TempId" runat="server" Value='<%# Bind("TempId") %>'  />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="System" HeaderText="System">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("System") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("System") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Vulnerability" HeaderText="Vulnerability">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="VulnerabilityType" HeaderText="VulnerabilityType">
                        <EditItemTemplate>
                           <asp:DropDownList ID="ddlType" runat="server" Width="140px" SelectedValue='<%# Eval("VulnerabilityType") %>'>
                                <asp:ListItem Value="0">--SELECT--</asp:ListItem>
                                <asp:ListItem Value="1">Suspicious</asp:ListItem>
                                <asp:ListItem Value="2">Exploitable</asp:ListItem>
                            </asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                             <asp:DropDownList ID="ddlType" runat="server" Width="140px" SelectedValue='<%# Eval("VulnerabilityType") %>'>
                                <asp:ListItem Value="0">--SELECT--</asp:ListItem>
                                <asp:ListItem Value="1">Suspicious</asp:ListItem>
                                <asp:ListItem Value="2">Exploitable</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Created" HeaderText="Created">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Created") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("Created") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Committed" HeaderText="Committed">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Committed") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("Committed") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
        </form>
    </body>
    </html>
    

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace TestingWeb
    {
        public partial class GridViewDemo : System.Web.UI.Page
        {
    
            //Mock repo
            private List<VulnerabilityToSystem> Vulnerabilities
            {
                get 
                {
                    if (ViewState["VulnerabilityToSystemList"] != null)
                    {
                        return ((List<VulnerabilityToSystem>)ViewState["VulnerabilityToSystemList"]).
                            OrderBy(m => m.VulnerabilityId).
                            ThenBy(m => m.SortOrder).ToList();
                    }
                    return GetVulnerabilities().OrderBy(m => m.VulnerabilityId).ThenBy(m => m.SortOrder).ToList();
                }
                set {
                    ViewState["VulnerabilityToSystemList"] = value;
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                string path = Server.MapPath(".");
    
                if (!Page.IsPostBack)
                {
                    Vulnerabilities = GetVulnerabilities();
                    BindGrid();
                }
                else {
                    UpdateGridDataSource();
                }
                
            }
    
            protected void UpdateGridDataSource()
            {
                foreach (GridViewRow row in GridView1.Rows)
                {
                    HiddenField uid = (HiddenField)row.FindControl("VulnerabilityToSystemId");
                    HiddenField gid = (HiddenField)row.FindControl("TempId");
                    DropDownList ddl = (DropDownList)row.FindControl("ddlType");
    
                    //Handle the new guid records
                    if (gid != null && gid.Value.ToString() != "00000000-0000-0000-0000-000000000000")
                    {
                        List<VulnerabilityToSystem> repo = Vulnerabilities;
                        VulnerabilityToSystem item;
                        item = (VulnerabilityToSystem)(from d in repo
                                                      where d.TempId == Guid.Parse(gid.Value)
                                                      select d).First();
    
                        item.VulnerabilityType = int.Parse(ddl.SelectedValue);
                    }
    
                    //handle the existing records
                    if (uid != null && uid.Value.ToString() != "0")
                    {
                        List<VulnerabilityToSystem> repo = Vulnerabilities;
                        VulnerabilityToSystem item;
                        item = (VulnerabilityToSystem)(from d in repo
                                                       where d.VulnerabilityToSystemId == int.Parse(uid.Value)
                                                       select d).First();
    
                        item.VulnerabilityType = int.Parse(ddl.SelectedValue);
                    }
                }
            }
    
            private void BindGrid()
            {
                GridView1.DataSource = Vulnerabilities;
                GridView1.DataBind();
            }
    
            //Command button click handler
            protected void addCmd_Command(object sender, CommandEventArgs e)
            {
                int id = 0;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (int.TryParse(e.CommandArgument.ToString(), out id))
                    { 
                        AddDuplicateRecordById(id);
                        BindGrid();
                    }
                }            
            }
            protected void removeCmd_Command(object sender, CommandEventArgs e)
            {
                Guid id;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (Guid.TryParse(e.CommandArgument.ToString(), out id))
                    {
                        RemoveRecordByGuid(id);
                        BindGrid();
                    }
                }            
            }
            
            private void RemoveRecordByGuid(Guid id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.TempId == id
                                              select d).First();
                repo.Remove(dup);
                Vulnerabilities = repo;
            }
    
    
            //Update Repo
            private void AddDuplicateRecordById(int id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
    
                //Create a copy
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.VulnerabilityToSystemId == id
                                              select new VulnerabilityToSystem()
                                              {
                                                  VulnerabilityToSystemId = 0,
                                                  TempId = Guid.NewGuid(),
                                                  VulnerabilityId = d.VulnerabilityId,
                                                  Name = d.Name,
                                                  System = d.System,
                                                  SystemId = d.SystemId,
                                                  Created = DateTime.Now,
                                                  SortOrder = d.SortOrder + 1,
                                                  Committed = false, 
                                                  VulnerabilityType = d.VulnerabilityType
                                              }).FirstOrDefault();
                //Persist the Update
                repo.Add(dup);
                Vulnerabilities = repo;
            }
    
            //Grid events
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                //might need this someday
            }
    
    
            //Mock data retrieval 
            protected List<VulnerabilityToSystem> GetVulnerabilities()
            {
                List<VulnerabilityToSystem> results = new List<VulnerabilityToSystem>();
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 1, VulnerabilityType = 1, Committed = true, SortOrder = 10, VulnerabilityId = 1, Name = "Injection", Created = new DateTime(2015, 1, 1), SystemId = 2, System = "Reporting" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 2, VulnerabilityType = 1, Committed = true, SortOrder = 20, VulnerabilityId = 2, Name = "Weak authentication and session management", Created = new DateTime(2015, 7, 1), SystemId = 1, System = "Login" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 3, VulnerabilityType = 1, Committed = true, SortOrder = 30, VulnerabilityId = 3, Name = "XSS", Created = new DateTime(2015, 12, 1), SystemId = 3, System = "Front End" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 4, VulnerabilityType = 1, Committed = true, SortOrder = 40, VulnerabilityId = 4, Name = "Insecure Direct Object References", Created = new DateTime(2016, 1, 4), SystemId = 1, System = "Services" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 5, VulnerabilityType = 1, Committed = true, SortOrder = 50, VulnerabilityId = 5, Name = "Security Misconfiguration", Created = new DateTime(2016, 1, 5), SystemId = 5, System = "Security" });
                return results;
            }
    
    
    
    
    
            
           
    
        }
        //Model
        [Serializable()]
        public class VulnerabilityToSystem {
            public int VulnerabilityToSystemId { get; set; }
            public Guid TempId { get; set; }
            public int VulnerabilityId { get; set; }
            public string Name { get; set; }
            public string System { get; set; }
            public int SystemId { get; set; }
            public DateTime Created { get; set; }
            public int SortOrder { get; set; }
            public bool Committed { get; set; }
            public int VulnerabilityType { get; set; } 
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 14, 2016 1:42 AM
  • User475983607 posted

    Its very close, the values get pulled from the front side by row however, the values are not repopulating. Here is my code at this point:

    Did you remember to set the bindings in the markup?

     <asp:DropDownList ID="ddlType" runat="server" Width="140px" SelectedValue='<%# Eval("VulnerabilityType") %>'>
    	<asp:ListItem Value="0">--SELECT--</asp:ListItem>
    	<asp:ListItem Value="1">Suspicious</asp:ListItem>
    	<asp:ListItem Value="2">Exploitable</asp:ListItem>
    </asp:DropDownList>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 14, 2016 4:25 PM

All replies

  • User475983607 posted

    Hello folks, I'm trying to get around a rather annoying problem. To add a row dynamically, it requires me to do a page postback which will wipe out anything I have entered on my gridview form. I suspect I am going to need to use session state to maintain the objects, however I do not have a huge amount of experience working with it so guidance is appreciated! Now, onto the code which I will include UI and C# code.

    The controls are data bound not dynamic so that makes this a little easier.  The tough part is dealing with possible multiple record updates on each post since the grid contains input elements on every row.  

    Be forewarned I had a few beers after work with the boys so you'll need to double check my work; int.Parse and Guid.Parse can be problematic.  

    Anyway, I added a dropdown that persists after clicking the add or remove buttons.  The trick is parsing the GridView early in the page life cycle to grab the submitted values and update the ViewState data store.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="TestingWeb.GridViewDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:TemplateField AccessibleHeaderText="Add" HeaderText="Add" ShowHeader="False">
                        <ItemTemplate>
                            <asp:LinkButton ID="addCmd" 
                                runat="server" 
                                CausesValidation="false" 
                                CommandName="add" 
                                Text="Add" 
                                CommandArgument='<%# Bind("VulnerabilityToSystemId") %>' 
                                OnCommand="addCmd_Command"></asp:LinkButton>
                            <asp:LinkButton ID="removeCmd" 
                                runat="server" 
                                CausesValidation="false" 
                                CommandName="delete" 
                                Text="Remove" 
                                CommandArgument='<%# Bind("TempId") %>' 
                                Visible ='<%# Eval("TempId").ToString() == "00000000-0000-0000-0000-000000000000" ? false : true  %>' 
                                OnCommand="removeCmd_Command"></asp:LinkButton>
                            <asp:HiddenField ID="VulnerabilityToSystemId" runat="server" Value='<%# Bind("VulnerabilityToSystemId") %>' />
                            <asp:HiddenField ID="VulnerabilityId" runat="server" Value='<%# Bind("VulnerabilityId") %>'  />
                            <asp:HiddenField ID="SystemId" runat="server" Value='<%# Bind("SystemId") %>'  />
                            <asp:HiddenField ID="TempId" runat="server" Value='<%# Bind("TempId") %>'  />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="System" HeaderText="System">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("System") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("System") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Vulnerability" HeaderText="Vulnerability">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="VulnerabilityType" HeaderText="VulnerabilityType">
                        <EditItemTemplate>
                           <asp:DropDownList ID="ddlType" runat="server" Width="140px" SelectedValue='<%# Eval("VulnerabilityType") %>'>
                                <asp:ListItem Value="0">--SELECT--</asp:ListItem>
                                <asp:ListItem Value="1">Suspicious</asp:ListItem>
                                <asp:ListItem Value="2">Exploitable</asp:ListItem>
                            </asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                             <asp:DropDownList ID="ddlType" runat="server" Width="140px" SelectedValue='<%# Eval("VulnerabilityType") %>'>
                                <asp:ListItem Value="0">--SELECT--</asp:ListItem>
                                <asp:ListItem Value="1">Suspicious</asp:ListItem>
                                <asp:ListItem Value="2">Exploitable</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Created" HeaderText="Created">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Created") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("Created") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Committed" HeaderText="Committed">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Committed") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("Committed") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
        </form>
    </body>
    </html>
    

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace TestingWeb
    {
        public partial class GridViewDemo : System.Web.UI.Page
        {
    
            //Mock repo
            private List<VulnerabilityToSystem> Vulnerabilities
            {
                get 
                {
                    if (ViewState["VulnerabilityToSystemList"] != null)
                    {
                        return ((List<VulnerabilityToSystem>)ViewState["VulnerabilityToSystemList"]).
                            OrderBy(m => m.VulnerabilityId).
                            ThenBy(m => m.SortOrder).ToList();
                    }
                    return GetVulnerabilities().OrderBy(m => m.VulnerabilityId).ThenBy(m => m.SortOrder).ToList();
                }
                set {
                    ViewState["VulnerabilityToSystemList"] = value;
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                string path = Server.MapPath(".");
    
                if (!Page.IsPostBack)
                {
                    Vulnerabilities = GetVulnerabilities();
                    BindGrid();
                }
                else {
                    UpdateGridDataSource();
                }
                
            }
    
            protected void UpdateGridDataSource()
            {
                foreach (GridViewRow row in GridView1.Rows)
                {
                    HiddenField uid = (HiddenField)row.FindControl("VulnerabilityToSystemId");
                    HiddenField gid = (HiddenField)row.FindControl("TempId");
                    DropDownList ddl = (DropDownList)row.FindControl("ddlType");
    
                    //Handle the new guid records
                    if (gid != null && gid.Value.ToString() != "00000000-0000-0000-0000-000000000000")
                    {
                        List<VulnerabilityToSystem> repo = Vulnerabilities;
                        VulnerabilityToSystem item;
                        item = (VulnerabilityToSystem)(from d in repo
                                                      where d.TempId == Guid.Parse(gid.Value)
                                                      select d).First();
    
                        item.VulnerabilityType = int.Parse(ddl.SelectedValue);
                    }
    
                    //handle the existing records
                    if (uid != null && uid.Value.ToString() != "0")
                    {
                        List<VulnerabilityToSystem> repo = Vulnerabilities;
                        VulnerabilityToSystem item;
                        item = (VulnerabilityToSystem)(from d in repo
                                                       where d.VulnerabilityToSystemId == int.Parse(uid.Value)
                                                       select d).First();
    
                        item.VulnerabilityType = int.Parse(ddl.SelectedValue);
                    }
                }
            }
    
            private void BindGrid()
            {
                GridView1.DataSource = Vulnerabilities;
                GridView1.DataBind();
            }
    
            //Command button click handler
            protected void addCmd_Command(object sender, CommandEventArgs e)
            {
                int id = 0;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (int.TryParse(e.CommandArgument.ToString(), out id))
                    { 
                        AddDuplicateRecordById(id);
                        BindGrid();
                    }
                }            
            }
            protected void removeCmd_Command(object sender, CommandEventArgs e)
            {
                Guid id;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (Guid.TryParse(e.CommandArgument.ToString(), out id))
                    {
                        RemoveRecordByGuid(id);
                        BindGrid();
                    }
                }            
            }
            
            private void RemoveRecordByGuid(Guid id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.TempId == id
                                              select d).First();
                repo.Remove(dup);
                Vulnerabilities = repo;
            }
    
    
            //Update Repo
            private void AddDuplicateRecordById(int id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
    
                //Create a copy
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.VulnerabilityToSystemId == id
                                              select new VulnerabilityToSystem()
                                              {
                                                  VulnerabilityToSystemId = 0,
                                                  TempId = Guid.NewGuid(),
                                                  VulnerabilityId = d.VulnerabilityId,
                                                  Name = d.Name,
                                                  System = d.System,
                                                  SystemId = d.SystemId,
                                                  Created = DateTime.Now,
                                                  SortOrder = d.SortOrder + 1,
                                                  Committed = false, 
                                                  VulnerabilityType = d.VulnerabilityType
                                              }).FirstOrDefault();
                //Persist the Update
                repo.Add(dup);
                Vulnerabilities = repo;
            }
    
            //Grid events
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                //might need this someday
            }
    
    
            //Mock data retrieval 
            protected List<VulnerabilityToSystem> GetVulnerabilities()
            {
                List<VulnerabilityToSystem> results = new List<VulnerabilityToSystem>();
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 1, VulnerabilityType = 1, Committed = true, SortOrder = 10, VulnerabilityId = 1, Name = "Injection", Created = new DateTime(2015, 1, 1), SystemId = 2, System = "Reporting" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 2, VulnerabilityType = 1, Committed = true, SortOrder = 20, VulnerabilityId = 2, Name = "Weak authentication and session management", Created = new DateTime(2015, 7, 1), SystemId = 1, System = "Login" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 3, VulnerabilityType = 1, Committed = true, SortOrder = 30, VulnerabilityId = 3, Name = "XSS", Created = new DateTime(2015, 12, 1), SystemId = 3, System = "Front End" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 4, VulnerabilityType = 1, Committed = true, SortOrder = 40, VulnerabilityId = 4, Name = "Insecure Direct Object References", Created = new DateTime(2016, 1, 4), SystemId = 1, System = "Services" });
                results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = 5, VulnerabilityType = 1, Committed = true, SortOrder = 50, VulnerabilityId = 5, Name = "Security Misconfiguration", Created = new DateTime(2016, 1, 5), SystemId = 5, System = "Security" });
                return results;
            }
    
    
    
    
    
            
           
    
        }
        //Model
        [Serializable()]
        public class VulnerabilityToSystem {
            public int VulnerabilityToSystemId { get; set; }
            public Guid TempId { get; set; }
            public int VulnerabilityId { get; set; }
            public string Name { get; set; }
            public string System { get; set; }
            public int SystemId { get; set; }
            public DateTime Created { get; set; }
            public int SortOrder { get; set; }
            public bool Committed { get; set; }
            public int VulnerabilityType { get; set; } 
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 14, 2016 1:42 AM
  • User-718146471 posted

    Its very close, the values get pulled from the front side by row however, the values are not repopulating. Here is my code at this point:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WASAuditSystem
    {
        public partial class GridViewDemo : System.Web.UI.Page
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
            //Mock repo
            private List<VulnerabilityToSystem> Vulnerabilities
            {
                get
                {
                    if (ViewState["VulnerabilityToSystemList"] != null)
                    {
                        return ((List<VulnerabilityToSystem>)ViewState["VulnerabilityToSystemList"]).
                            OrderBy(m => m.VulnerabilityId).
                            ThenBy(m => m.SortOrder).ToList();
                    }
                    return GetVulnerabilities().OrderBy(m => m.VulnerabilityId).ThenBy(m => m.SortOrder).ToList();
                }
                set
                {
                    ViewState["VulnerabilityToSystemList"] = value;
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    Vulnerabilities = GetVulnerabilities();
                    BindGrid();
                }
                else
                {
                    UpdateGridDataSource();
                }
    
            }
    
            private void BindGrid()
            {
                GridView1.DataSource = Vulnerabilities;
                GridView1.DataBind();
            }
    
            protected void UpdateGridDataSource()
            {
                foreach (GridViewRow row in GridView1.Rows)
                {
                    HiddenField uid = (HiddenField)row.FindControl("VulnerabilityToSystemId");
                    HiddenField gid = (HiddenField)row.FindControl("TempId");
                    DropDownList ddl = (DropDownList)row.FindControl("ddlType");
                    TextBox txt = (TextBox)row.FindControl("txtCount");
                    CheckBox cb = (CheckBox)row.FindControl("cbVulnName");
    
                    //Handle the new guid records
                    if (gid != null && gid.Value.ToString() != "00000000-0000-0000-0000-000000000000")
                    {
                        List<VulnerabilityToSystem> repo = Vulnerabilities;
                        VulnerabilityToSystem item;
                        item = (VulnerabilityToSystem)(from d in repo
                                                       where d.TempId == Guid.Parse(gid.Value)
                                                       select d).First();
    
                        item.type = ddl.SelectedValue;
                        item.count = txt.Text.ToString();
                        item.cbVulnName = cb.Checked;
                    }
    
                    //handle the existing records
                    if (uid != null && uid.Value.ToString() != "0")
                    {
                        List<VulnerabilityToSystem> repo = Vulnerabilities;
                        VulnerabilityToSystem item;
                        item = (VulnerabilityToSystem)(from d in repo
                                                       where d.VulnerabilityToSystemId == int.Parse(uid.Value)
                                                       select d).First();
    
                        item.type = ddl.SelectedValue;
                        item.count = txt.Text.ToString();
                        item.cbVulnName = cb.Checked;
                    }
                }
            }
    
    
            //Command button click handler
            protected void addCmd_Command(object sender, CommandEventArgs e)
            {
                int id = 0;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (int.TryParse(e.CommandArgument.ToString(), out id))
                    {
                        AddDuplicateRecordById(id);
                        BindGrid();
                    }
                }
            }
    
            protected void removeCmd_Command(object sender, CommandEventArgs e)
            {
                Guid id;
                if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
                {
                    if (Guid.TryParse(e.CommandArgument.ToString(), out id))
                    {
                        RemoveRecordByGuid(id);
                        BindGrid();
                    }
                }
            }
    
            private void RemoveRecordByGuid(Guid id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.TempId == id
                                              select d).First();
                repo.Remove(dup);
                Vulnerabilities = repo;
            }
    
            //Update Repo
            private void AddDuplicateRecordById(int id)
            {
                List<VulnerabilityToSystem> repo = Vulnerabilities;
                VulnerabilityToSystem dup = new VulnerabilityToSystem();
    
                //Create a copy
                dup = (VulnerabilityToSystem)(from d in repo
                                              where d.VulnerabilityToSystemId == id
                                              select new VulnerabilityToSystem()
                                              {
                                                  VulnerabilityToSystemId = 0,
                                                  VulnerabilityId = d.VulnerabilityId,
                                                  TempId = Guid.NewGuid(),
                                                  Vuln_Name=d.Vuln_Name,
                                                  type = d.type,
                                                  count = d.count,
                                                  Vuln_Reference = d.Vuln_Reference,
                                                  SortOrder = d.SortOrder + 1,
                                              }).FirstOrDefault();
                //Persist the Update
                repo.Add(dup);
                Vulnerabilities = repo;
            }
    
            //Mock data retrieval 
            protected List<VulnerabilityToSystem> GetVulnerabilities()
            {
                List<VulnerabilityToSystem> results = new List<VulnerabilityToSystem>();
                int i = 0;
                string SQLQuery = "SELECT Vuln_Name, Vuln_Reference FROM Vulnerabilities";
                SqlCommand cmd = new SqlCommand(SQLQuery, conn);
                conn.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    results.Add(new VulnerabilityToSystem() { VulnerabilityToSystemId = i, VulnerabilityId = i, Vuln_Name = rdr.GetValue(0).ToString(), count = "0", type = "-- SELECT --", Vuln_Reference = rdr.GetValue(1).ToString() });
                    i++;
                }
                return results;
            }
    
            protected void btnPrepare_Click(object sender, EventArgs e)
            {            
                Label1.Text = string.Empty;
                CheckBox tempC;
                Label tempCName;
                DropDownList ddlC;
                TextBox txtC;
                Label t1;
                int index = 1;
    
                Label1.Text += String.Format("<table style='border-spacing:2px; spacing:10px; padding:10px; border:solid;' width='100%'><tr style='background-color:#3399FF; text-transform: uppercase; color: white; font-weight: bolder;'><td>Name</td><td>Risk Level</td><td>Count</td><td>Reference</td></tr>");
                string vulnBoth = string.Empty, vulncount = string.Empty, vulntype = string.Empty;
                try
                {
                    foreach (GridViewRow row in GridView1.Rows)
                    {
                        tempC = (CheckBox)row.FindControl("cbVulnName");
                        if ((row.RowType == DataControlRowType.DataRow) && (tempC.Checked))
                        {
                            tempCName = (Label)row.FindControl("lblVulnName");
                            ddlC = (DropDownList)row.FindControl("ddlType");
                            t1 = (Label)row.FindControl("lblComments");
                            txtC = (TextBox)row.FindControl("txtCount");
                            if (t1.Text == null)
                            {
                                t1.Text = string.Empty;
                            }
                            if (index % 2 == 0)
                            {
                                Label1.Text += String.Format("<tr style='background-color:#CCEEFF;'>");
                                Label1.Text += String.Format("<td>{0}</td>", tempCName.Text);
                                Label1.Text += String.Format("<td>{0}</td>", ddlC.SelectedValue);
                                Label1.Text += String.Format("<td>{0}</td>", txtC.Text);
                                Label1.Text += String.Format("<td><a href={0}>Reference</a></td></tr>", t1.Text);
                                index++;
                            }
                            else
                            {
                                Label1.Text += String.Format("<tr style='background-color:#FFFFFF;'>");
                                Label1.Text += String.Format("<td>{0}</td>", tempCName.Text);
                                Label1.Text += String.Format("<td>{0}</td>", ddlC.SelectedValue);
                                Label1.Text += String.Format("<td>{0}</td>", txtC.Text);
                                Label1.Text += String.Format("<td><a href={0}>Reference</a></td></tr>", t1.Text);
                                index++;
                            }
                            if (tempC.Checked)
                            {
                                if ((txtC.Text.ToString() == string.Empty) & (ddlC.SelectedIndex == 0))
                                {
                                    vulnBoth = vulnBoth + "<br />You selected " + tempCName.Text.ToString() + " however you forgot to enter the count and select the vulnerability.";
                                }
                                else if (txtC.Text.ToString() == string.Empty)
                                {
                                    vulncount = vulncount + "<br />You selected " + tempCName.Text.ToString() + " however you forgot to enter the count.";
                                }
                                else if (ddlC.SelectedIndex == 0)
                                {
                                    vulntype = vulntype + "<br />You selected " + tempCName.Text.ToString() + " however you forgot to select the vulnerability type.";
                                }
                                lblBothErr.Text = vulnBoth.ToString();
                                lblCountErr.Text = vulncount.ToString();
                                lblTypeErr.Text = vulntype.ToString();
                            }
                        }
                        //ScriptManager.RegisterStartupScript(Page, typeof(Page), "GVErrors", "setTimeout(GVErrors, 1);", true);
                    }
                    try
                    {
                        if (rfAuditor.IsValid == true)
                        {
                            rfAuditor.Visible = false;
                        }
                        else
                        {
                            rfAuditor.Visible = true;
                            SetFocus(rfAuditor);
                        }
                        if (rfvAppName.IsValid == true)
                        {
                            rfvAppName.Visible = false;
                        }
                        else
                        {
                            rfvAppName.Visible = true;
                            SetFocus(rfvAppName);
                        }
                        if (rfvDevEmail.IsValid == true)
                        {
                            rfvDevEmail.Visible = false;
                        }
                        else
                        {
                            rfvDevEmail.Visible = true;
                            SetFocus(rfvDevEmail);
                        }
                    }
                    catch (Exception ex)
                    {
    
                    }
                    Label1.Text += String.Format("</table>");
                    btnSubmit.Visible = true;
                    if ((rfvDevEmail.IsValid = false) | (rfvAppName.IsValid = false) | (rfAuditor.IsValid = false) | (lblBothErr.Text != string.Empty) | (lblTypeErr.Text != string.Empty) | (lblCountErr.Text != string.Empty))
                    {
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnSubmit.Visible = true;
                    }
                }
                catch (Exception ex)
                {
    
                }
            }
    
            protected void btnSubmit_Click(object sender, EventArgs e)
            {
                string htmlBody = "Hello, I have audited " + txtAppName.Text.ToString() + ".<br><br>We have found the following issues. Please reply in SSC with your comments/fixes.<br><br>" + Label1.Text.ToString();
                htmlBody = htmlBody + "<br><br>Please let me know if you have any questions.<br><br>Respectfully,<br><br>" + ddlAuditor.SelectedItem.ToString() + "";
                string fromAddr = ddlAuditor.SelectedValue.ToString();
                string ccAddr = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
                string ccMulti = txtCCDevs.Text.ToString();
                string toAddr = txtDevEmail.Text.ToString();
                string Subject = "Application Evaluation: " + txtAppName.Text.ToString();
    
                try
                {
                    smtpHelper.SendMailMessage(fromAddr.ToString(), toAddr.ToString(), ccAddr.ToString(), txtCCDevs.Text.ToString(), Subject.ToString(), htmlBody.ToString());
                    ClearTextBoxes(Page);
                    Label1.Text = string.Empty;
                    btnSubmit.Visible = false;
                    GridView1.DataSource = Vulnerabilities;
                    GridView1.DataBind();
                    Response.Write("Successfully Sent.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.ToString());
                }
    
            }
    
            protected void ClearTextBoxes(Control p1)
            {
                foreach (Control ctrl in p1.Controls)
                {
    
                    if (ctrl is TextBox)
                    {
                        TextBox t = ctrl as TextBox;
    
                        if (t != null)
                        {
                            t.Text = String.Empty;
                        }
                    }
                    if (ctrl is CheckBox)
                    {
                        CheckBox cb = ctrl as CheckBox;
    
                        if (cb != null)
                        {
                            cb.Checked = false;
                        }
                    }
                    else
                    {
                        if (ctrl.Controls.Count > 0)
                        {
                            ClearTextBoxes(ctrl);
                        }
                    }
                }
            }
        }
        //Model
        [Serializable()]
        public class VulnerabilityToSystem
        {
            public int VulnerabilityToSystemId { get; set; }
            public int VulnerabilityId { get; set; }
            public Guid TempId { get; set; }
            public bool cbVulnName { get; set; }
            public string Vuln_Name { get; set; }
            public string count { get; set; }
            public string type { get; set; }
            public int SortOrder { get; set; }
            public string Vuln_Reference { get; set; }
        }
    }

    Thursday, January 14, 2016 2:58 PM
  • User475983607 posted

    Its very close, the values get pulled from the front side by row however, the values are not repopulating. Here is my code at this point:

    Did you remember to set the bindings in the markup?

     <asp:DropDownList ID="ddlType" runat="server" Width="140px" SelectedValue='<%# Eval("VulnerabilityType") %>'>
    	<asp:ListItem Value="0">--SELECT--</asp:ListItem>
    	<asp:ListItem Value="1">Suspicious</asp:ListItem>
    	<asp:ListItem Value="2">Exploitable</asp:ListItem>
    </asp:DropDownList>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 14, 2016 4:25 PM
  • User-718146471 posted

    Ah, that's what I was missing, thank you! Working great :)

    Thursday, January 14, 2016 5:31 PM