473,394 Members | 1,854 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Save temporary gridview value into database

5
Hi.
I'm developing a code where it will store temporary data into gridview from textbox,and the value will have a link to google search.

Now i want to save the values to database,according to appropriate table column that matches the gridview value.

Any ideas guys?
Here's the code :
Expand|Select|Wrap|Line Numbers
  1. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
  2.  
  3.  
  4.  <title>Temporary Data</title>
  5.  
  6.     <script type="text/javascript"
  7.         src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
  8.     </script>
  9.  
  10.     <script type="text/javascript">
  11.  
  12.         $(function() {
  13.             $('input:text:first').focus();
  14.             var $inp = $('.cls');
  15.             $inp.bind('keydown', function(e) {
  16.                 //var key = (e.keyCode ? e.keyCode : e.charCode);
  17.                 var key = e.which;
  18.                 if (key == 13) {
  19.                     document.getElementById('btnSearch').click();
  20.  
  21.                 }
  22.             });
  23.         });
  24.     </script>
  25.  
  26.     <script runat="server">
  27.         static DataTable dt;
  28.         protected void Page_Load(object sender, EventArgs e)
  29.         {
  30.             {
  31.                 if (!Page.IsPostBack)
  32.                 {
  33.                     //Instantiating the DataTable;
  34.                     dt = new DataTable("Table1");
  35.  
  36.                     //Adding Columns
  37.                     dt.Columns.Add("name", typeof(string));
  38.  
  39.                 }
  40.  
  41.             }
  42.         }
  43.         protected void BtnAddToTable_Click(object sender, EventArgs e)
  44.         {
  45.             dt.Rows.Add(TxtName.Text);
  46.             BindData();
  47.             TxtName.Text = String.Empty;
  48.  
  49.         }
  50.  
  51.         public void BindData()
  52.         {
  53.             GridView1.DataSource = dt;
  54.             GridView1.DataBind();
  55.         }
  56.  
  57.         protected void BtnDelete_Click(object sender, EventArgs e)
  58.         {
  59.             string sid = string.Empty;
  60.             string sname = string.Empty;
  61.             Button cb = sender as Button;
  62.             GridViewRow grow = (GridViewRow)cb.NamingContainer;
  63.             dt.Rows.RemoveAt(grow.RowIndex);
  64.             BindData();
  65.         }
  66.  
  67.         protected void BtnSendToDatabase_Click(object sender, EventArgs e)
  68.         {
  69.             SqlConnection conn = new SqlConnection();
  70.             conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  71.  
  72.             SqlCommand cmd = new SqlCommand();
  73.             cmd.CommandText = "INSERT INTO Table1 (Company_Name) VALUES ('" + "" + "')";
  74.             cmd.Connection = conn;
  75.  
  76.             conn.Open();
  77.             cmd.ExecuteNonQuery();
  78.             conn.Close();
  79.  
  80.             Response.Write("Record saved into Database");
  81.         }
  82.  
  83.  
  84.         </script>
  85.  
  86.     <body>
  87.  
  88.     <div>
  89.     <table >
  90.     <tr>
  91.     <td class="style1">
  92.     <asp:Label ID="Label1" runat="server" Text="Caller Info :"></asp:Label>
  93.     </td>
  94.     <td style="width: 100px">
  95.     <asp:TextBox ID="TxtName" runat="server" class="cls" onekeypress=""  ToolTip="Press Enter key for new input"></asp:TextBox>
  96.     </td>
  97.     </tr>
  98.  
  99.     </table>
  100.  
  101.  
  102.     <asp:Button ID="BtnAddToTable" runat="server" align="right" class="cls" 
  103.     Text="Add" OnClick="BtnAddToTable_Click" />
  104.  
  105.  
  106.     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
  107.     <Columns>
  108.     <asp:TemplateField HeaderText="Caller Information">
  109.     <ItemTemplate>
  110.     <a onclick='document.getElementById("<%=iframe1.ClientID%>").src = this.href; return false;' href='http://www.google.com/#q=<%#DataBinder.Eval(Container.DataItem,"name")%>'>
  111.     <%#DataBinder.Eval(Container.DataItem,"name")%></a>
  112.  
  113.     </ItemTemplate>
  114.     </asp:TemplateField>
  115.  
  116.     <asp:TemplateField HeaderText="">
  117.     <ItemTemplate>
  118.     <asp:Button ID="BtnDelete" runat="server" Text="Clear" OnClick="BtnDelete_Click" />
  119.     </ItemTemplate>
  120.     </asp:TemplateField>
  121.     </Columns>
  122.     </asp:GridView>
  123.  
  124.     <iframe runat="server" id="iframe1" src="" class="cls"
  125.      style="z-index: 105; left: 225px; position: absolute; top: 109px; width: 875px; height: 455px;" frameborder="1" title="Google Search Display" ></iframe>     
  126.  
  127. </div>
  128.  
  129.         <asp:Button ID="BtnSendToDatabase" runat="server" class="cls" Text="//Sent to database" OnClick="BtnSendToDatabase_Click" />
  130.  
  131. </body>
  132.  
  133. </asp:Content>
  134.  
I use the back code as a script.
Sep 13 '10 #1
9 3693
Frinavale
9,735 Expert Mod 8TB
Ok?

It looks like you're doing everything fine except that your SQL Insert Into statement isn't actually doing anything.

You need to loop through each row in your DataTable and call the Insert Into statement for that row/record. You currently are not doing that.

Also, it is not good to insert user-provided values directly into your SQL query because it leaves you open to a SQL Injection Attack. Instead of adding the values to be inserted into your database by concatenating them into the string that contains your SQL command, use parameters.

Please review the following article that has an example of how to use Parameters:
Database tutorial Part 1

-Frinny
Sep 14 '10 #2
samgee
5
I just want to know the method on how to get the temporary values in the gridview and then save to database.
Sep 15 '10 #3
Frinavale
9,735 Expert Mod 8TB
Loop through each DataRow in the DataTable.Rows, access the "name" field.

Like this:
Expand|Select|Wrap|Line Numbers
  1. // For each row, retrieve the value in the name field.
  2. foreach(DataRow myRow in dt.Rows){
  3.  string name = myRow("name");
  4. //......
  5. }
  6.  
-Frinny
Sep 15 '10 #4
samgee
5
Hi.
I try to apply your code by using parameter.
But it gives me error.
Here's the cs code :
Expand|Select|Wrap|Line Numbers
  1.  protected void BtnSendToDatabase_Click(object sender, EventArgs e)
  2.         {
  3.             foreach (DataRow row in dt.Rows)
  4.             {
  5.                 Console.WriteLine(row["name"].ToString());
  6.             }
  7.  
  8.             SqlCommand cmd = new SqlCommand();
  9.             cmd.CommandText = "INSERT INTO Table1 (Company_Name) VALUES (@compName)";
  10.             cmd.Parameters.AddWithValue("@compName", TxtName.Text);
  11.  
  12.             foreach (DataRow row in dt.Rows)
  13.             {
  14.                 cmd.Parameter.AddWithValue("@compName", row["name"].ToString());
  15.                 cmd.ExecuteNonQuery();
  16.             }
  17.  
  18.             cmd.Dispose();
  19.             conn.Close();
  20.             conn.Dispose();
  21.         }
  22.  
But i'm getting this error:
CS1061: 'System.Data.SqlClient.SqlCommand' does not contain a definition for 'Parameter' and no extension method 'Parameter' accepting a first argument of type 'System.Data.SqlClient.SqlCommand' could be found (are you missing a using directive or an assembly reference?)
Source error:

cmd.Parameter.AddWithValue("@compName", row["name"].ToString());


I tried to use command instead of cmd,but it still gives error.

Any ideas?
Sep 17 '10 #5
Frinavale
9,735 Expert Mod 8TB
If use the "Add" method instead and set the parameter in the loop. You are trying to add the @compName parameter more than once.

-Frinny
Sep 20 '10 #6
samgee
5
Sorry,but i dont get you..
Sep 20 '10 #7
Frinavale
9,735 Expert Mod 8TB
Just call the Add method once.
Do not call it in the loop.

Expand|Select|Wrap|Line Numbers
  1.  protected void BtnSendToDatabase_Click(object sender, EventArgs e)
  2.         {
  3.             foreach (DataRow row in dt.Rows)
  4.             {
  5.                 Console.WriteLine(row["name"].ToString());
  6.             }
  7.  
  8.             SqlCommand cmd = new SqlCommand();
  9.             cmd.CommandText = "INSERT INTO Table1 (Company_Name) VALUES (@compName)";
  10.             cmd.Parameters.Add("@compName", SqlDbType.VarChar);
  11.  
  12.             foreach (DataRow row in dt.Rows)
  13.             {
  14.                 cmd.Parameters.Item["@compName"].Value = row["name"].ToString();
  15.                 cmd.ExecuteNonQuery();
  16.             }
  17.  
  18.             cmd.Dispose();
  19.             conn.Close();
  20.             conn.Dispose();
  21.         }
Sep 20 '10 #8
samgee
5
How about the connection string?
Sep 21 '10 #9
Frinavale
9,735 Expert Mod 8TB
You could provide the connection string to the SqlCommand constructor so that the SqlCommand is initialized with it. It might help you to look over the MSDN documentation on the SqlCommand Class.

-Frinny
Sep 21 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: SOAP | last post by:
how to save binary data to database by using CMP2.0? I would like to save a save image to database through EJB. but I don't know which data type shoud I use. any examples? thanks a lot
2
by: joe | last post by:
Can i save a session to database
1
by: Irene | last post by:
Hello all! I'm creating a web site in ASP.NET (VB.NET). One of the requirements was to allow users to create orders going through several steps. A must have is to have an option to save the work...
0
by: craig dunn | last post by:
I've used the code from the post for a while now... but recently upgraded to SQL Server 2005. I've written a new script for SQL Server 2005, which can be found at...
2
by: cgd | last post by:
how to do Save Word document to Database in memory, not through the disk
1
by: Ashu Saxena | last post by:
Hi ! I'm a php developer. I'm developing a site into which I have to upload a text file and a image file from users through a browse box and then I have to retrieve that file and save it into...
1
slapshock
by: slapshock | last post by:
hi every one.... i am new in c#.net.... i want to know on how to upload images and save it to the database... please give me the exact code on how to do it.... i need the code in doing my...
1
by: plusplus | last post by:
Hi, How can i save datagrid contents to database? Database i'm using is MySQL. Thanks lots! (:
3
by: raamay | last post by:
hey experts, please advise me what is the best way to save multiple checkboxes value in a database. I have 6 checkboxes and i came across storing the values in a single column of a table which i dont...
7
omerbutt
by: omerbutt | last post by:
hi i have an applicationa for online test in there i have to save some questions in the db now when i try to save this question what is 2 + 2 ? when i save it in the database it removes the +...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.