locked
How to insert DataValueField into database.... from gridview ? RRS feed

  • Question

  • User-367318540 posted

    i am inserting multiple data into gridview from dropdown list ,i have bind dropdownlist data from database where DataTextField and DataValueField  are coming....Now i want to store DatavalueField in session of multiple row of gridview data,,then i insert bulk data into database...

    here is my code

    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;
    using System.Data.SqlClient;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection("Data Source=DESKTOP-5PJ76B9;Integrated Security=SSPI;Initial Catalog=SPS;MultipleActiveResultSets=True;");
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                    itemload();
                }
            }
    
            private void itemload()
            {
              
                con.Open();
                SqlDataAdapter adpr1 = new SqlDataAdapter("select * from ItemMasterFile ", con);
                DataSet dspr1 = new DataSet();
                adpr1.Fill(dspr1);
                DropDownList1.DataSource = dspr1.Tables[0];
                DropDownList1.DataTextField = "Descriptionitem";
                DropDownList1.DataValueField = "Codeitem";
                DropDownList1.DataBind();
            }
    
            private void BindGrid()
            {
                GridView1.DataSource = DataSource;
                GridView1.DataBind();
            }
    
            private DataTable DataSource
            {
                //-- this is the property that will retain the data source and data will keep on adding in there on button click
                get
                {
                    DataTable dtSource = new DataTable();
                    if (null != Session["__DataSource"])
                        dtSource = Session["__DataSource"] as DataTable;
                    else
                        dtSource = GetDataFromDatabase();
    
                    return dtSource;
                }
    
                set
                {
                    Session["__DataSource"] = value;
                }
            }
    
            private DataTable GetDataFromDatabase()
            {
                //-- here is a sample code, that just generate data for Gridview, you will require to write code here to fetch data from Database.
                DataTable resultDt = new DataTable();
                resultDt.Columns.AddRange(
                    new DataColumn[] {
            new DataColumn("Descriptionitem"),
            new DataColumn("QTY"),
         
                });
    
                for (int i = 0; i < 0; i++)
                {
                    DataRow dr = resultDt.NewRow();
                    //dr["Field1"] = "Field1 " + i.ToString();
                    //dr["Field2"] = "Field2 " + i.ToString();
                    //dr["Field3"] = "Field3 " + i.ToString();
                    resultDt.Rows.Add(dr);
                }
    
                return resultDt;
            }
    
            protected void btnSave_Click(object sender, EventArgs e)
            {
                DataTable dtSource = DataSource;
                DataRow dr = dtSource.NewRow();
                dr["Descriptionitem"] = DropDownList1.SelectedItem.Text.Trim();
    
               // dr["Descriptionitem"] = DropDownList1.Text.Trim();
                dr["QTY"] = txtqty.Text.Trim();
           
    
                dtSource.Rows.Add(dr);
                DataSource = dtSource;
    
                BindGrid();
    
                txtqty.Text = string.Empty;
            }
        }
    }

    Please Consider

    Tuesday, August 6, 2019 11:21 AM

Answers

  • User288213138 posted

    Hi akhterr,

    According to your description, I made a demo for your reference.

    I put the DatavalueField of dropdownlist in session and bind it to GridView, then convert the session to a datatable and insert the value into the database by traversing the datatable.


    The code:

    <div>
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                <asp:GridView ID="GridView1" runat="server"></asp:GridView>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
                <asp:GridView ID="GridView2" runat="server"></asp:GridView>
            </div>
    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindDrop();
                    BindGrid();
                }
            }        
            public void BindDrop()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customer"))
                    {
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                DropDownList1.DataSource = dt;
                                DropDownList1.DataTextField = "Name";
                                DropDownList1.DataValueField = "customerId";                           
                                DropDownList1.DataBind();
                            }
                        }
                    }
                }
            }
            public void BindGrid()
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[] { new DataColumn("customerId") });
                foreach (ListItem item in DropDownList1.Items)
                {
                    dt.Rows.Add(item.Value);
                   
                }
                Session["Customers"] = dt;
                GridView1.DataSource = (DataTable)Session["Customers"];
                GridView1.DataBind();
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                DataTable dt = (DataTable)Session["Customers"];
    
                for (int i = 0; i < dt.Rows.Count; i++)
                {
    
                    var a = dt.Rows[i]["customerId"].ToString().Trim();
                    string query = "INSERT INTO ID VALUES(@Id)";
                    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        using (SqlCommand cmd = new SqlCommand(query))
                        {
                            cmd.Parameters.AddWithValue("@Id", a);
                            cmd.Connection = con;
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                }
            }
    

    Best regard,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 7, 2019 8:47 AM