Member 13320426 Ответов: 1

Остановите двойной вывод при запуске программы


using System.Data.SqlClient;
using System.Data;
using System;
using System.Linq;
using System.Web.UI.WebControls;
using java.util;
using System.Configuration;
using Microsoft.VisualBasic;

namespace Intranet.WebApp.Feedback.Surveys.Survey
{
    public partial class Questions : System.Web.UI.Page
    {

        private bool InstanceFieldsInitialized = false;

        private Questions()
        {
            if (!InstanceFieldsInitialized)
            {
                InitializeInstanceFields();
                InstanceFieldsInitialized = true;
            }
        }

        private void InitializeInstanceFields()
        {
            r = User.Identity.Name;
        }

        private ArrayList @params = new ArrayList();
        string r;
        private ArrayList pklist = new ArrayList();

        //Dynamically Loads the Questions based off of the table.
        protected void Page_Load(object sender, System.EventArgs e)
        {
            //Questions Loaded

            string proc = "Question_Select";
            SqlConnection QuestionsConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
            SqlCommand QuestionsCommand = new SqlCommand(proc, QuestionsConnection);
            QuestionsCommand.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(QuestionsCommand);
            DataTable vTable = new DataTable();
            da.Fill(vTable);




            Table detailsTable = new Table();
            detailsTable.CellSpacing = 10;
            var i = 0;

            foreach (DataRow row in vTable.Rows)
            {
                var value = vTable.Rows[i][0].ToString();
                TableRow tRow = new TableRow();
                TableCell tCell1 = new TableCell();
                TableCell tCell2 = new TableCell();
                var pk = vTable.Rows[i][1].ToString();
                pklist.add(pk);

                Label myLabel = new Label();

                myLabel.CssClass = "bold";

                TextBox myText = new TextBox();

                myText.TextMode = TextBoxMode.MultiLine;
                myText.Columns = 40;
                myText.Rows = 4;
                myText.ID = "Box" + i;
                @params.add(myText.ID);

                myLabel.Text = string.Format("{0}. {1}", i + 1, value);
                tCell1.Controls.Add(myLabel);
                tCell2.Controls.Add(myText);
                tRow.Cells.Add(tCell1);
                tRow.Cells.Add(tCell2);

                detailsTable.Rows.Add(tRow);
                i += 1;
            }
            Panel1.Controls.Add(detailsTable);

        }


        //INSTANT C# WARNING: Strict 'Handles' conversion only applies to fields declared in the same class - the event will be wired in 'SubscribeToEvents':
        //ORIGINAL LINE: Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        protected void Button1_Click(object sender, EventArgs e)
        {

            //When a survey is completed, this method checks to see who completed the survey and insert them into a table.
            string proc2 = "User_Insert";
            SqlConnection ResponsesConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
            SqlCommand ResponsesCommand2 = new SqlCommand(proc2, ResponsesConnection2);
            ResponsesCommand2.CommandType = CommandType.StoredProcedure;

            ResponsesCommand2.Parameters.AddWithValue("@UserName", r);
            ResponsesConnection2.Open();
            ResponsesConnection2 = (SqlConnection)ResponsesCommand2.ExecuteScalar();

            //   Establish connection and set up command to use stored procedure
            string proc = "Responses_Insert";
            SqlConnection ResponsesConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
            SqlCommand ResponsesCommand = new SqlCommand(proc, ResponsesConnection);
            ResponsesCommand.CommandType = CommandType.StoredProcedure;

            ResponsesConnection.Open();
            var i = 0;
            for (int a = 0; a < @params.ToString().Count(); a++)
            {
                ResponsesCommand.Parameters.Clear();
                TextBox textbox = Panel1.FindControl(@params.ToString().ElementAt(a).ToString()) as TextBox;
                ResponsesCommand.Parameters.AddWithValue("@QuestionID", pklist.ToString().ElementAt(i).ToString());
                ResponsesCommand.Parameters.AddWithValue("@response", textbox.Text);
                ResponsesCommand.Parameters.AddWithValue("@UserName", r);
                ResponsesConnection = (SqlConnection)ResponsesCommand.ExecuteScalar();
                i += 1;

            }


            Microsoft.VisualBasic.Interaction.MsgBox("Thank you for completing the survey.", Microsoft.VisualBasic.MsgBoxStyle.MsgBoxSetForeground, "Survey Complete");



            Response.Redirect("../../../Default.aspx");

        }
        //Button to see if a person has chosen to be marked annonymous.
        //INSTANT C# WARNING: Strict 'Handles' conversion only applies to fields declared in the same class - the event will be wired in 'SubscribeToEvents':
        //ORIGINAL LINE: Protected Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles Checkbox1.CheckedChanged
        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (Checkbox1.Checked == false)
            {
                r = User.Identity.Name;
            }
            else
            {
                r = "Anonymous";
            }
        }
    }
}


Что я уже пробовал:

Я конвертирую Vb в C#. Я не могу понять, почему он печатает вопросы опроса дважды. Используется 3 различных преобразователя кода.

1 Ответов

Рейтинг:
2

Patrice T

Цитата:
Я не могу понять, почему он печатает вопросы опроса дважды.

Используйте отладчик, чтобы увидеть, что делает ваш код.

Существует инструмент, который позволяет вам видеть, что делает ваш код, его имя отладчик Это также отличный инструмент обучения, потому что он показывает вам реальность, и вы можете увидеть, какие ожидания соответствуют реальности.
Когда вы не понимаете, что делает ваш код или почему он делает то, что делает, ответ таков: отладчик.
Используйте отладчик, чтобы увидеть, что делает ваш код. Просто установите точку останова и посмотрите, как работает ваш код, отладчик позволит вам выполнять строки 1 на 1 и проверять переменные по мере их выполнения.

Отладчик-Википедия, свободная энциклопедия[^]

Освоение отладки в Visual Studio 2010 - руководство для начинающих[^]
Базовая отладка с помощью Visual Studio 2010-YouTube[^]
Отладчик здесь для того, чтобы показать вам, что делает ваш код, и ваша задача-сравнить его с тем, что он должен делать.
В отладчике нет никакой магии, он не находит ошибок, он просто помогает вам. Когда код не делает того, что ожидается, вы близки к ошибке.