josef_alex Ответов: 1

Сохранение динамических значений текстового поля из GridView в базу данных


Я получаю ожидаемую ошибку перечисления делегатов классов интерфейса или структуры в приведенном ниже коде .Я пробовал несколько разных способов, но не могу заставить его работать .
Я включил свою строку подключения, которая была настроена в веб-конфигурации .любая информация, которую вы можете дать, будет очень полезна.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Text;
using System.Data.OleDb;

 namespace WebApplication8
{
    public partial class WebForm2 : System.Web.UI.Page
    {


       }
}
//connection string in web.config
//<configuration>
  //<connectionstrings>
   // <add name="ApplicationServices" connectionstring="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true">
    //  providerName="System.Data.SqlClient" />
    //<add name="DtbConnectionString" connectionstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dtb.accdb">
    //  providerName="System.Data.OleDb" />
 // </add></add></connectionstrings>


 private string GetConnectionString()
    
        
{  
      return 
System.Configuration.ConfigurationManager.ConnectionStrings["DtbConnectionString"].ConnectionString;
    }



 

    private void InsertRecords(StringCollection sc)
    {
        oledbConnection conn = new oledbConnection(GetConnectionString());
        StringBuilder sb = new StringBuilder(string.Empty);
        string[] splitItems = null;
        foreach (string item in sc)
        {
 
            const string sqlStatement = "INSERT INTO SampleTable (Column1,Column2,Column3) VALUES";
            if (item.Contains(","))
            {
                splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
            }
 
        }
 
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
 
           //Display a popup which indicates that the record was successfully inserted
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
 
        }
        catch (System.Data.oledb.oledbException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
 
        }
        finally
        {
            conn.Close();
        }
    }
 

 
protected void Button1_Click(object sender, EventArgs e)
{
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
 
                    //get the values from the TextBoxes
                    //then add it to the collections with a comma "," as the delimited values
                    sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
                    rowIndex++;
                }
                //Call the method for executing inserts
                InsertRecords(sc);
            }
        }
}  </configuration>

1 Ответов

Рейтинг:
1

Pravin Patil, Mumbai

Из вашего кода видно, что вы получаете эту ошибку, потому что вы помещаете все свои методы вне класса WebForm2 Поместите все методы в определение класса или просто скопируйте следующий код.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Text;
using System.Data.OleDb;
 
 namespace WebApplication8
{
    public partial class WebForm2 : System.Web.UI.Page
    {
 private string GetConnectionString()
    
        
{  
      return 
System.Configuration.ConfigurationManager.ConnectionStrings["DtbConnectionString"].ConnectionString;
    }
 

 
 
 
    private void InsertRecords(StringCollection sc)
    {
        oledbConnection conn = new oledbConnection(GetConnectionString());
        StringBuilder sb = new StringBuilder(string.Empty);
        string[] splitItems = null;
        foreach (string item in sc)
        {
 
            const string sqlStatement = "INSERT INTO SampleTable (Column1,Column2,Column3) VALUES";
            if (item.Contains(","))
            {
                splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
            }
 
        }
 
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
 
           //Display a popup which indicates that the record was successfully inserted
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
 
        }
        catch (System.Data.oledb.oledbException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
 
        }
        finally
        {
            conn.Close();
        }
    }
 
 
 
protected void Button1_Click(object sender, EventArgs e)
{
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
 
                    //get the values from the TextBoxes
                    //then add it to the collections with a comma "," as the delimited values
                    sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
                    rowIndex++;
                }
                //Call the method for executing inserts
                InsertRecords(sc);
            }
        }
}
}


Надеюсь, это поможет.
Всего наилучшего.


Member 11316594

тот же код в vb.net -пожалуйста...