根据数据库条目的数量自动创建标签';s c#asp.net mssql

本文关键字:标签 mssql net c#asp 创建 数据库 | 更新日期: 2023-09-27 18:25:15

有没有一种方法可以根据数据库中的用户条目数量生成标签,并在页面加载时将数据库信息打印到标签上。

我试图通过绑定数据来实现这一点,但我发现我只能在网格格式中实现,我不想要网格。

我试图创建的总体调查是将问题存储在数据库中并显示在标签上。我希望有人能够将问题添加到数据库中,并为其自动生成显示问题的标签。

我可以得到我想要的效果,但我已经添加了标签,并手动在上面写下了问题。如果有人能提供帮助或建议,如果可以的话,我们将不胜感激。提前谢谢。

以下是我目前所拥有的:

<h1>&nbsp;</h1>
    <h1>PaaS Assured Server Test</h1>
     <div class="row">
        <div class="col-md-6">
                <h2>
                    <asp:Label ID="lblmsg" runat="server"></asp:Label>
                <asp:Panel ID="BugPanel1" runat="server" BorderColor="#FFFF99" BackColor="#FFFF99" Visible="False">
                    <asp:Label ID="Label4" runat="server" Text="You have informed us of an error." ForeColor="Black"></asp:Label>
                    <br /><asp:Label ID="Label3" runat="server" Text="Please advise of serverity. 1 - highest 5 - lowest:" ForeColor="Black"></asp:Label>
                   &nbsp; <asp:DropDownList ID="SeverityList1" runat="server" AutoPostBack="True">
                        <asp:ListItem>1</asp:ListItem>
                        <asp:ListItem>2</asp:ListItem>
                        <asp:ListItem>3</asp:ListItem>
                        <asp:ListItem>4</asp:ListItem>
                        <asp:ListItem>5</asp:ListItem>
                    </asp:DropDownList>
                    <br /><asp:Label ID="Label5" runat="server" Text="Who shall be notified of the error:" ForeColor="Black"></asp:Label>
                &nbsp; <asp:DropDownList ID="NotifyList1" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True">
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [UserName] FROM [AspNetUsers]"></asp:SqlDataSource>
                <br /><asp:Label ID="Label6" runat="server" Text="Would you like a copy emailed to yourself?" ForeColor="Black"></asp:Label>
                    <asp:RadioButtonList ID="EmailRadio1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
                        <asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
                        <asp:ListItem Value="True" Text="Yes">No</asp:ListItem>
                    </asp:RadioButtonList>
                    <asp:Button ID="BugButton" runat="server" Text="File Bug and Generate Report" CausesValidation="False" OnClick="BugButton_Click" />
                </asp:Panel>

                 </h2>
            <h2>Provisioning</h2>
        <hr />
            <asp:Panel ID="FormPanel1" runat="server" BackColor="#F4F4F4">
            <asp:Panel ID="HeadPanel1" runat="server" BackColor="#E4E4E4" BorderColor="#999999" Font-Bold="True" ForeColor="#000066" Font-Underline="True">
            <h3>Page View</h3>
            </asp:Panel>
            <asp:RequiredFieldValidator ID="Radio1Validator" runat="server" ErrorMessage="Error: Please select an option:" ControlToValidate="Radio1" SetFocusOnError="True" ForeColor="Red"></asp:RequiredFieldValidator>
                  <p />
            <asp:Label ID="PALabel1" runat="server" Text="Does your screen look similar to the image displayed ?"></asp:Label>&nbsp;
            <asp:ImageButton ID="ImageButton1" runat="server" Height="20px" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton1_Click" Width="21px" CausesValidation="False" /><br/>     
            <asp:RadioButtonList ID="Radio1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
                        <asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
                        <asp:ListItem Text="No" Value="False">No</asp:ListItem>
                  </asp:RadioButtonList>
                <asp:Panel ID="PAPanel1" runat="server">
                    <asp:Label ID="Label1" runat="server" ForeColor="#000099" Text="Provide further details:"></asp:Label>
                    <asp:TextBox ID="PAText1" runat="server" BorderColor="Silver" CssClass="form-control"></asp:TextBox>
                </asp:Panel>
                <p />
                <asp:RequiredFieldValidator ID="Radio2Validator" runat="server" ControlToValidate="Radio2" ErrorMessage="Error: Please select an option:" ForeColor="Red"></asp:RequiredFieldValidator>
                <p />
                <asp:Label ID="PALabel2" runat="server" Text="In &quot;Server Name&quot; is virtual pre-selected?"></asp:Label>
                &nbsp;
                <asp:ImageButton ID="ImageButton4" height="20px" runat="server" Width="21px" CausesValidation="False" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton4_Click" />
            <br/>         
            <asp:RadioButtonList ID="Radio2" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
                        <asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
                        <asp:ListItem Text="No" Value="False">No</asp:ListItem>
                  </asp:RadioButtonList>
           <asp:Panel ID="PAPanel2" runat="server">     
               <asp:Label ID="Label2" runat="server" Text="Provide further details:" ForeColor="#000099"></asp:Label>
               <asp:TextBox ID="PAText2" runat="server" CssClass="form-control" BorderColor="Silver"   ></asp:TextBox>
           </asp:Panel>
                <asp:Panel ID="HeadPanel2" runat="server" BackColor="#E4E4E4" BorderColor="#999999" Font-Bold="True" ForeColor="#000066" Font-Underline="True">
            <h3>Form details</h3>
            </asp:Panel>
                 <asp:Panel ID="SubHead1" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
            <h4>Request Details</h4>
            </asp:Panel>
                 <asp:Panel ID="SubHead2" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
            <h4>Server Location</h4>
            </asp:Panel>
            <asp:Panel ID="SubHead3" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
            <h4>Product and Support Details</h4>
            </asp:Panel>
            <asp:Panel ID="SubHead4" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
            <h4>Server Configuration</h4>
            </asp:Panel>
            <asp:Label ID="PALabel3" runat="server" Text="What operating system are you testing?"></asp:Label>
                &nbsp;
            <asp:ImageButton ID="ImageButton3" runat="server" Height="20px" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton1_Click" Width="21px" CausesValidation="False" /><br/>         
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please select the server you are testing:" ControlToValidate="Radio3" ForeColor="Red"></asp:RequiredFieldValidator>
                <asp:RadioButtonList ID="Radio3" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
                    <asp:ListItem Value="Windows 2008 Server R2" Text="Windows 2008 Server R2">Windows 2008 Server R2</asp:ListItem>
                    <asp:ListItem Value="Windows 2012 Server R2" Text="Windows 2012 Server R2">Windows 2012 Server R2</asp:ListItem>
                    <asp:ListItem Value="RHEL" Text="RHEL">RHEL</asp:ListItem>
                </asp:RadioButtonList>
              <p />&nbsp;<p />
                    <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Submit"/>
                    <p />
                    &nbsp;</asp:Panel>

        </div>        


        <div class="col-md-6">
       <h2>&nbsp;</h2>
            <h2>Information Viewer &nbsp;&nbsp;<asp:Image ID="LrgInfoImage" runat="server" ImageUrl="~/Image/PrintScreen/Info.jpg" Height="21px" Width="24px" /> 
                &nbsp&nbsp<asp:Button ID="Button2" runat="server" Text="View test history" BorderColor="#ECECFF" BorderStyle="Ridge" CssClass="btn" Font-Underline="True" ForeColor="#0066FF" Height="32px" OnClick="Button2_Click" Width="177px" CausesValidation="False" />
            </h2> <hr />
            <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
                <asp:View ID="View0" runat="server">
               <div style="overflow-x:auto;width:600px" class="fixed">
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="PAssuredId" DataSourceID="SqlDataSource1" AllowSorting="True" BorderColor="#F4F4F4" ForeColor="#000066" GridLines="Horizontal" Width="56%" HorizontalAlign="Center">
                        <AlternatingRowStyle BackColor="#F4F4FF" BorderColor="Black" ForeColor="#000066" />
                        <Columns>
                            <asp:BoundField DataField="PAssuredId" HeaderText="Test ID" InsertVisible="False" ReadOnly="True" SortExpression="PAssuredId" NullDisplayText="INVALID TEST" ItemStyle-BackColor="#F0F0FF" />
                            <asp:BoundField DataField="Date" HeaderText="Date/ Time" SortExpression="Date" />
                            <asp:BoundField DataField="UserName" HeaderText="User" SortExpression="UserName" NullDisplayText="INVALID TEST" />
                            <asp:BoundField DataField="Platform" HeaderText="Platform" SortExpression="Platform" NullDisplayText="User did not select platform" />
                            <asp:CheckBoxField DataField="VirtualPreselect" HeaderText="Virtual" SortExpression="VirtualPreselect" />
                            <asp:CheckBoxField DataField="DetsAccurate" HeaderText="Details ok?" SortExpression="DetsAccurate" />
                            <asp:CheckBoxField DataField="ScreenSame" HeaderText="Correct form?" SortExpression="ScreenSame" />
                            <asp:BoundField DataField="No1" HeaderText="Error 1" SortExpression="No1" NullDisplayText="No error found" ReadOnly="True" />
                            <asp:BoundField DataField="No2" HeaderText="Error 2" SortExpression="No2" NullDisplayText="No error found" />
                            <asp:BoundField DataField="No3" HeaderText="Error 3" SortExpression="No3" NullDisplayText="No error found" />
                            <asp:BoundField DataField="No4" HeaderText="Error 4" SortExpression="No4" NullDisplayText="No error found" />
                            <asp:BoundField DataField="No5" HeaderText="Error 5" SortExpression="No5" NullDisplayText="No error found" />
                        </Columns>
                    </asp:GridView>    
                    </div>
                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT PaaSAssuredServer.PAssuredId, PaaSAssuredServer.Date, AspNetUsers.UserName, PaaSAssuredServer.Platform, PaaSAssuredServer.VirtualPreselect, PaaSAssuredServer.DetsAccurate, PaaSAssuredServer.ScreenSame, PaaSAssuredServer.No1, PaaSAssuredServer.No2, PaaSAssuredServer.No3, PaaSAssuredServer.No4, PaaSAssuredServer.No5 FROM PaaSAssuredServer INNER JOIN AspNetUsers ON PaaSAssuredServer.UserId = AspNetUsers.Id ORDER BY PaaSAssuredServer.Date DESC"></asp:SqlDataSource>
                </asp:View>
                <asp:View ID="View1" runat="server">
                    <asp:Image ID="ScreenImge" runat="server" Height="600px" ImageUrl="~/Image/PrintScreen/PassTest1.jpg" Width="600px" />
                </asp:View>
                <asp:View ID="View2" runat="server">
                    <asp:Image ID="Image1" runat="server" Height="105px" ImageUrl="~/Image/PrintScreen/ServerType.jpg" Width="446px" />
                </asp:View>
                <asp:View ID="View3" runat="server">
                    <asp:Image ID="Image2" runat="server" ImageUrl="~/Image/PrintScreen/ServerType.jpg" Height="105px" Width="446px" />
                </asp:View>
            </asp:MultiView>
        </div>
            </div>
</asp:Content>

这是背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Windows.Forms;
using Microsoft.AspNet.Identity;

namespace IRISTest
{
    public partial class PaaSAssuredServer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Radio1.SelectedValue == "False")
            {
                PAPanel1.Visible = true;
            }
            else
            {
                PAPanel1.Visible = false;
            }
            if (Radio2.SelectedValue == "False")
            {
                PAPanel2.Visible = true;
            }
            else
            {
                PAPanel2.Visible = false;
            }
        }
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;
        }
        protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
        {
            MultiView1.ActiveViewIndex = 3;
        }
        protected void Submit(object sender, EventArgs e)
        {
            {
                string message = "I can confirm the following:" + Environment.NewLine + "It is " + Radio1.SelectedValue + " that my screen matches that displayed in the image. " + Environment.NewLine +
                                  "It is:" + Radio2.SelectedValue + " that my default Server Name is set to Virtual. " + Environment.NewLine +
                                  "I have follwed the steps accurately and provided all requested information/ further details to enable further investigation" + Environment.NewLine +
                                  "On hitting sumbit I am confirming that I have perfomed this test and the provided information is accurate to my knowledge.";
                string caption = "Confirmation:";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                MessageBoxIcon icon = MessageBoxIcon.Information;
                MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
                DialogResult result;
                result = MessageBox.Show(message, caption, buttons, icon, defaultbutton);
                if (result == DialogResult.Yes)
                {
                    Int32 newProdID = 0;
                    var userId = User.Identity.GetUserId();
                    var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        SqlCommand cmd = new SqlCommand("INSERT INTO [PaaSAssuredServer] ([VirtualPreselect], [No1], [No2], [ScreenSame], [Date], [UserId], [Platform]) VALUES ( @VirtualPreselect, @No1, @No2, @ScreenSame, @Date, @UserId, @Platform);" + "SELECT CAST(scope_identity() AS int)");
                        //cmd.CommandType = CommandType.Text;
                        cmd.Connection = connection;
                        cmd.Parameters.AddWithValue("@ScreenSame", Radio1.SelectedItem.Value);
                        cmd.Parameters.AddWithValue("@VirtualPreselect", Radio2.SelectedItem.Value);
                        cmd.Parameters.AddWithValue("@No1", PAText1.Text);
                        cmd.Parameters.AddWithValue("@No2", PAText2.Text);
                        cmd.Parameters.AddWithValue("@Date", DateTime.Now);
                        cmd.Parameters.AddWithValue("@UserId", userId);
                        cmd.Parameters.AddWithValue("@Platform", Radio3.SelectedItem.Value);
                        //cmd.Parameters.AddWithValue("@UserId", 0);
                        //cmd.Parameters["@UserId"].Direction = ParameterDirection.InputOutput;
                        connection.Open();
                        try
                        {
                            newProdID = (Int32)cmd.ExecuteScalar();
                            //int UserId = (int)cmd.Parameters["@UserId"].Value;
                            //cmd.ExecuteNonQuery();
                            //var rowCount = cmd.ExecuteScalar();
                            lblmsg.Text = "You have completed and recorded the test Sucessfully " + Environment.NewLine +
                                "Your test number is: " + newProdID;
                            lblmsg.ForeColor = System.Drawing.Color.Green;
                        }
                        catch (SqlException sqlEx)
                        {
                            lblmsg.Text = sqlEx.Message;
                            lblmsg.ForeColor = System.Drawing.Color.Red;
                        }
                        finally
                        {
                            connection.Close();
                        }
                        if (PAText1.Text == "0")
                        {
                            BugPanel1.Visible = true;
                        }
                        else
                        {
                            BugPanel1.Visible = false;
                        }
                        if (PAText2.Text == "0")
                        {
                            BugPanel1.Visible = true;
                        }
                        else
                        {
                            BugPanel1.Visible = false;
                        }
                    }
                }
            }
        }
        protected void BugButton_Click(object sender, EventArgs e)
        {
            Int32 newProdID1 = 0;
            var userId = User.Identity.GetUserId();
            var BugTest = true;

            var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("INSERT INTO [BugRep] ([Bug], [Serverity], [CorrName], [UserId]) VALUES (@Bug, @Serverity, @CorrName, @UserId);" + "SELECT CAST(scope_identity() AS int)");
                //cmd.CommandType = CommandType.Text;
                cmd.Connection = connection;
                cmd.Parameters.AddWithValue("@Serverity", SeverityList1.SelectedItem.Value);
                cmd.Parameters.AddWithValue("@CorrName", NotifyList1.SelectedItem.Value);
                cmd.Parameters.AddWithValue("@Bug", BugTest);
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Parameters.AddWithValue("@Platform", Radio3.SelectedItem.Value);
                //cmd.Parameters.AddWithValue("@UserId", 0);
                //cmd.Parameters["@UserId"].Direction = ParameterDirection.InputOutput;
                connection.Open();
                try
                {
                    newProdID1 = (Int32)cmd.ExecuteScalar();
                    //int UserId = (int)cmd.Parameters["@UserId"].Value;
                    //cmd.ExecuteNonQuery();
                    //var rowCount = cmd.ExecuteScalar();
                    lblmsg.Text = "You have reported the bug sucessfully and" + NotifyList1.SelectedItem.Value + "has been informed." + Environment.NewLine +
                        "Your test number is: " + newProdID1;
                    lblmsg.ForeColor = System.Drawing.Color.Green;
                }
                catch (SqlException sqlEx)
                {
                    lblmsg.Text = sqlEx.Message;
                    lblmsg.ForeColor = System.Drawing.Color.Red;
                }
                finally
                {
                    connection.Close();
                }
            }






        }
    }
}

根据数据库条目的数量自动创建标签';s c#asp.net mssql

使用数据绑定是正确的。如果你想对生成的HTML有更多的控制,你可以使用Repeater控件。通过这种方式,您可以为要显示的项目指定模板。

以下示例显示了一个中继器。在ItemTemplate中,HiddenField存储问题id,Label显示文本。当请求页面时,将从数据库中检索项目(示例使用测试数据)并将其绑定到Repeater。我还在ItemTemplate中添加了一个下拉列表,以便用户可以选择答案。单击"保存"按钮后,将从中继器项目中的控件中检索值。

ASPX

<asp:Repeater ID="rpt" runat="server">
     <ItemTemplate>
         <p>
             <asp:HiddenField ID="hiddenId" runat="server" Value='<%# Eval("Id") %>' />
             <asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("Text") %>' />
             <asp:DropDownList ID="ddlAnswer" runat="server">
                 <asp:ListItem Text="1" />
                 <asp:ListItem Text="2" />
                 <asp:ListItem Text="3" />
             </asp:DropDownList>
         </p>
     </ItemTemplate>
 </asp:Repeater>
 <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />

代码隐藏

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            var questions = GetQuestions();
            rpt.DataSource = questions;
            rpt.DataBind();
        }
    }
    private IEnumerable<Question> GetQuestions()
    {
        // Load questions from database
        // Setting up some sample data for this sample
        var lst = new List<Question>();
        return Enumerable.Range(1, 5).Select(x => new Question() { Id = x, Text = "Question " + x.ToString() });
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var dictAnswers = GetValuesFromRepeater();
        // Save answers to database
    }
    private IDictionary<int, int> GetValuesFromRepeater()
    {
        var dict = new Dictionary<int, int>();
        foreach (RepeaterItem item in rpt.Items)
        {
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
            {
                var id = int.Parse(((HiddenField)item.FindControl("hiddenId")).Value);
                var answer = int.Parse(((DropDownList)item.FindControl("ddlAnswer")).Text);
                dict.Add(id, answer);
            }
        }
        return dict;
    }
}
public class Question
{
    public int Id { get; set; }
    public string Text { get; set; }
}

请注意,当从中继器检索值时,必须使用FindControl方法根据控件的id找到控件。

SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand ("select fields from database", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow dr in DataSet.Tables[0].Rows){
    Label lbl = new Label();
    lbl.Text = dr["column"].ToString() + ":";
    TextBox txt = new TextBox();
    txt.ID = "txt" + dr["id"].ToString();
}

你必须把它推进!IsPostBack

保存时,您必须将所有ID放入某个数组或列表中,并使用foreach数组:

foreach (int id in id_array){
    command.Parameters.AddWithValue("@"+param+id.ToString(), (TextBox)(Page.FindControlById("txt"+id.ToString())).Text);
}

但您也必须考虑您的sql_query(在代码隐藏或存储过程中,根据params编号使其具有响应性)。希望它能帮助