I'm a newbie in Visual Studio and I want to make a database system that allows the user to insert, update, delete and search data using a Windows Forms application.
I already watched 3 tutorial how but I'm getting the same error. when I delete my ExecuteNonQuery() call, it doesn't have any error but the data I entered into my textboxes is not inserted into my database. When I put it back I'm getting this kind of error
ERROR:
CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace EaglePlannersDatabase
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void InsertButton_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand cmd = new SqlCommand("Insert Into EAGLEPLANNERS(policy number,plan type,renewal date,name,age,address,birthday,email,home/office number,mode of payment,amount) values (#policy number,#plan type,#renewal date,#name,#age,#address,#birthday,#email,#home/office number,#mode of payment,#amount)", connection);
cmd.Parameters.AddWithValue("#policy number", int.Parse(policyNumbertxtbox.Text));
cmd.Parameters.AddWithValue("#plan type", planTypetxtbox.Text);
cmd.Parameters.AddWithValue("#renewal date", int.Parse(renewalDatetxtbox.Text));
cmd.Parameters.AddWithValue("#name", nametxtbox.Text);
cmd.Parameters.AddWithValue("#age", int.Parse(agetxtbox.Text));
cmd.Parameters.AddWithValue("#address", addresstxtbox.Text);
cmd.Parameters.AddWithValue("#birthday", int.Parse(birthdaytxtbox.Text));
cmd.Parameters.AddWithValue("#email", (emailtxtbox.Text));
cmd.Parameters.AddWithValue("#home/office number", int.Parse(homeofficetxtbox.Text));
cmd.Parameters.AddWithValue("#mode of payment", (modeofpaymenttxtbox.Text));
cmd.Parameters.AddWithValue("#amount", int.Parse(amounttxtbox.Text));
cmd.ExecuteNonQuery();
connection.Close();
policyNumbertxtbox.Text = "";
planTypetxtbox.Text = "";
renewalDatetxtbox.Text = "";
nametxtbox.Text = "";
agetxtbox.Text = "";
addresstxtbox.Text = "";
birthdaytxtbox.Text = "";
emailtxtbox.Text = "";
homeofficetxtbox.Text = "";
modeofpaymenttxtbox.Text = "";
amounttxtbox.Text = "";
MessageBox.Show("Record inserted successfully!");
}
}
}
As a newbie, getting the pieces working first, then applying to the user interface I would apply second. I will try to summarize each piece. First your connection itself looked strange as others have pointed out. I would try to first make sure the connection itself works before applying any attempt at sql insert/update/delete going on. So you might try
SqlConnection connection = new SqlConnection(
#"Data Source (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;
Integrated Security=True;
Connect Timeout=30" );
private void TestConnect()
{
if( connection.Open() )
// great, you have a good connection
connection.Close();
else
// message to yourself why a failed connection and fix it...
}
Once you know your connection is good, then on to your sql-insert. Having good column names is important. Dont try to be fancy with human readable with spaces types of column names, just causes headaches. Use simple and direct as others have pointed out in prior comments. Also, when parameterizing, I have tried to always slightly alter the insert/update/delete parameters with a "p" prefix indicating the PARAMETER FOR the column, such as
insert into SomeTable ( oneColumn, secondCol ) values ( #pOneColumn, #pSecondCol )
just to avoid bad confusion. If an error comes out via "oneColumn" vs "pOneColumn" in the message, you KNOW which thing is at fault. The column itself does not work, or the specific parameter/value being supplied.
Next, readability of your SQL statements, especially as they get longer. Use spaces and I typically use a leading "#" before the quoted sql command to allow for line continuations as I edited your previous answer. So the same above insert would be written more like
var cmd = new SqlCommand(
#"insert into SomeTable
( oneColumn,
secondCol
)
values
( #pOneColumn,
#pSecondCol
)", connection );
So if you ever needed to add additional columns (or remove), you can see the paired set of insert columns vs parameters much easier.
Now the testing. Don't try to work off some user-entered values, put in known VALID values so you dont have to worry about user entered values. Get the command to WORK, then pull values from interface later. (continuing from above sample)
cmd.Parameters.AddWithValue("#pOneColumn", 17 );
cmd.Parameters.AddWithValue("#pSecondCol", "some Text");
Then try to execute that and make sure IT works. Once it does, THEN start pulling from your user interface
cmd.Parameters.AddWithValue("#pOneColumn", int.Parse( yourTextControl.Text ));
cmd.Parameters.AddWithValue("#pSecondCol", anotherTextControl.Text );
Find your mistakes BEFORE you let any human interaction get into and screw-up the rest of what you think SHOULD work.
Note, if you make public properties to your view models such as
public int someAge {get; set;}
and then set the bindings of the data entry control in the screen to this someAge property, it will only allow a numeric entry to be entered and will otherwise have a value of zero if someone tries to put in text. Similarly if you are dealing with dates, and if date/time, always use datetime fields for querying purposes vs formatted date as a text field. You will thank yourself in the future when querying for things within date range periods. HTH
Finally,try to avoid using AddWithValue. Instead, properly identify the expected data type as described in the linked article. I just left original context to your code for testing and debug researching purposes.
This would be the possible answer on your question, what I have done here, first I changed your connection string by removing AttachDbFilename attribute, and replace that by adding of Initial Catalog attribute where I set the name of your database.
Next thing, I declared variables where the values from textboxes will be stored, these values of variables will be our parameters, this is not necessary to do, it is just my own style, you can keep as you done.
I have seen also, that you are not using try/catch/finally block and you are closing the connection in the same part of code where you opening the connection, and maybe that is the reason why your values are not being stored into the table, so I decided to round your code within that block. If you don't know what is try/catch/finally block you can read the documentation here . We are opening the connection and do all operations on database in try block, in catch block we are catching all errors that might be caused in our application and in finally we are closing the connection. You will also notice that I created additional check, where I checking the result of ExecuteNonQuery() method, and if result of ExecuteNonQuery method is equals to 1 - records is inserted successfully, otherwise it fails.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace EaglePlannersDatabase
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=EaglePlannersDataBase;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void InsertButton_Click(object sender, EventArgs e)
{
int policyNumber = Convert.ToInt32(policyNumbertxtbox.Text);
string planType = planTypetxtbox.Text;
int renewalDate = Convert.ToInt32(renewalDatetxtbox.Text);
string name = nametxtbox.Text;
int age = Convert.ToInt32(agetxtbox.Text);
string address = addresstxtbox.Text;
int birthday = Convert.ToInt32(birthdaytxtbox.Text);
string email = emailtxtbox.Text;
int homeOfficeNumber = Convert.ToInt32(homeofficetxtbox.Text);
string modeOfPayment = modeofpaymenttxtbox.Text;
int amount = Convert.ToInt32(amounttxtbox.Text);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("Insert Into tbl1 (PolicyNumber,planType,renewalDate,name,age,address,birthday,email,homeOfficeNumber,modeOfPayment,amount) values (#PolicyNumber,#planType,#renewalDate,#name,#age,#address,#birthday,#email,#homeOfficeNumber,#modeOfPayment,#amount)", connection);
cmd.Parameters.AddWithValue("#PolicyNumber",policyNumber);
cmd.Parameters.AddWithValue("#planType",planType);
cmd.Parameters.AddWithValue("#renewalDate",renewalDate);
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#age",age);
cmd.Parameters.AddWithValue("#address",address);
cmd.Parameters.AddWithValue("#birthday",birthday);
cmd.Parameters.AddWithValue("#email",email);
cmd.Parameters.AddWithValue("#homeOfficeNumber",homeOfficeNumber);
cmd.Parameters.AddWithValue("#modeOfPayment",modeOfPayment);
cmd.Parameters.AddWithValue("#amount",amount);
int result = cmd.ExecuteNonQuery();
if(result == 1)
{
MessageBox.Show("Record Inserted Successfully!");
policyNumbertxtbox.Text = "";
planTypetxtbox.Text = "";
renewalDatetxtbox.Text = "";
nametxtbox.Text = "";
agetxtbox.Text = "";
addresstxtbox.Text = "";
birthdaytxtbox.Text = "";
emailtxtbox.Text = "";
homeofficetxtbox.Text = "";
modeofpaymenttxtbox.Text = "";
amounttxtbox.Text = "";
}
else
{
MessageBox.Show("Something went wrong!");
}
}
catch(SqlException ex)
{
MessageBox.Show("We have found error with operation on database: " + ex.Message);
}
catch(Exception ex)
{
MessageBox.Show("We have found error in your code: " + ex.Message);
}
finally
{
connection.Close();
}
}
}
}
here's my new code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace EaglePlannersDatabase
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void InsertButton_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand cmd = new SqlCommand(
#"Insert Into tbl1
( PolicyNumber,
planType,
renewalDate,
name,
age,
address,
birthday,
email,
homeOfficeNumber,
modeOfPayment,
amount )
values
( #PolicyNumber,
#planType,
#renewalDate,
#name,
#age,
#address,
#birthday,
#email,
#homeOfficeNumber,
#modeOfPayment,
#amount )", connection);
cmd.Parameters.AddWithValue("#PolicyNumber", int.Parse(policyNumbertxtbox.Text));
cmd.Parameters.AddWithValue("#planType", planTypetxtbox.Text);
cmd.Parameters.AddWithValue("#renewalDate", int.Parse(renewalDatetxtbox.Text));
cmd.Parameters.AddWithValue("#name", nametxtbox.Text);
cmd.Parameters.AddWithValue("#age", int.Parse(agetxtbox.Text));
cmd.Parameters.AddWithValue("#address", addresstxtbox.Text);
cmd.Parameters.AddWithValue("#birthday", int.Parse(birthdaytxtbox.Text));
cmd.Parameters.AddWithValue("#email", (emailtxtbox.Text));
cmd.Parameters.AddWithValue("#homeOfficeNumber", int.Parse(homeofficetxtbox.Text));
cmd.Parameters.AddWithValue("#modeOfPayment", (modeofpaymenttxtbox.Text));
cmd.Parameters.AddWithValue("#amount", int.Parse(amounttxtbox.Text));
cmd.ExecuteNonQuery();
connection.Close();
policyNumbertxtbox.Text = "";
planTypetxtbox.Text = "";
renewalDatetxtbox.Text = "";
nametxtbox.Text = "";
agetxtbox.Text = "";
addresstxtbox.Text = "";
birthdaytxtbox.Text = "";
emailtxtbox.Text = "";
homeofficetxtbox.Text = "";
modeofpaymenttxtbox.Text = "";
amounttxtbox.Text = "";
MessageBox.Show("Record Inserted Successfully!");
}
}
}
here's my database
I'm trying to read a CSV file into a table that I have created in Visual Studio. I want to validate the values in the file to see if they are correct, if all the values pass the checks, it will go into the table. If any values are not correct, an error report will be created using a JSON file.
I have already got some test data ready but I'm not sure how to separate the correct data from the incorrect data after the checker are complete.
public partial class NHSBatchChecker : Form
{
public NHSBatchChecker()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\Users\wy6282\Desktop\VS\NHSBATCHCHECKER\Test.txt"; // Start in C: drive
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.DefaultExt = "txt"; // Extension of file is txt only
openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files allowed
openFileDialog1.CheckFileExists = true; // Error message if file does not exist
openFileDialog1.CheckPathExists = true; // Error message if invalid file path
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string connectionstring;
SqlConnection cnn;
connectionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\wy6282\Desktop\VS\NHSBATCHCHECKER\nhsBatchChecker\Results.mdf;Integrated Security=True";
cnn = new SqlConnection(connectionstring);
cnn.Open();
SqlCommand command;
SqlDataAdapter adaper = new SqlDataAdapter();
string sql = "";
sql = "Insert into Results(NHS Number, Date of Birth, First Name, Last Name, Title, Gender) values()";
command = new SqlCommand(sql, cnn);
adaper.InsertCommand = new SqlCommand(sql, cnn);
adaper.InsertCommand.ExecuteNonQuery();
command.Dispose();
cnn.Close();
How do I add my valid records into the sql table?
you're trying to do too much in one go.
rule number 1: always split your problem into manageable junks:
read data from CSV.
filter incorrect data
save filtered data to database.
Now you have 3 distinct pieces of work to focus on.
Reading data from a CSV is trivial, there are many libraries that can help with that. Do a bit of research and pick one.
Create a class which holds the properties you need for validation checks and also those you want saved in the database.
Your goal is to create a list of these objects, one per row in csv. Of course, you may not be able to read everything in one go depending on how much data your csv holds, but you can pick a library which can deal with whatever size you have.
Now you have a list of objects. Write an algorithm which determines what is valid and what not, based on the rules you need. Your goal here is to end up with a possibly smaller list of the same objects, chucking out the invalid ones.
Save whatever is left in the database.
You need to start thinking about how you organize you code, don't just throw everything into the Click event of a button. You can create a model class to hold your objects, maybe create a separate class library where you can put your csv reading method.
Another class library perhaps for your filtering algorithm(s).
Your Click event should be fairly slim and only call library methods when it needs to do something. This is separation of concerns or SOC, which is a Solid Principle.
I am not sure how you plan to validate the datapoints, but the code below shows how to pull data from a CSV and load it into a SQL Server table.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string server = "EXCEL-PC\\EXCELDEVELOPER";
string database = "AdventureWorksLT2012";
string SQLServerConnectionString = String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI", server, database);
string CSVpath = #"C:\Users\Ryan\Documents\Visual Studio 2010\Projects\Bulk Copy from CSV to SQL Server Table\WindowsFormsApplication1\bin"; // CSV file Path
string CSVFileConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};;Extended Properties=\"text;HDR=Yes;FMT=Delimited\";", CSVpath);
var AllFiles = new DirectoryInfo(CSVpath).GetFiles("*.CSV");
string File_Name = string.Empty;
foreach (var file in AllFiles)
{
try
{
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(CSVFileConnectionString))
{
con.Open();
var csvQuery = string.Format("select * from [{0}]", file.Name);
using (OleDbDataAdapter da = new OleDbDataAdapter(csvQuery, con))
{
da.Fill(dt);
}
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLServerConnectionString))
{
bulkCopy.ColumnMappings.Add(0, "MyGroup");
bulkCopy.ColumnMappings.Add(1, "ID");
bulkCopy.ColumnMappings.Add(2, "Name");
bulkCopy.ColumnMappings.Add(3, "Address");
bulkCopy.ColumnMappings.Add(4, "Country");
bulkCopy.DestinationTableName = "AllEmployees";
bulkCopy.BatchSize = 0;
bulkCopy.WriteToServer(dt);
bulkCopy.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
}
this is a piece of code which is showing exception. It take sql query entered in text from textbox on the Window form (testform) and display the result in excel sheet. how can i take value in string to so that it dont show exception and that sql1 is textbox name is empty function in Testform.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Windows.Forms;
using Exceloutput_Application;
public class ProcessDataset
{
public ProcessDataset()
{
}
public static DataTable ReadTable()
{
TestForm t = new TestForm();
var returnValue = new DataTable();
var conn = new SqlConnection(ConnectionString._connectionString);
string st = t.sql1.Text;
try
{
conn.Open();
var command = new SqlCommand(st, conn);
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(returnValue);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
return returnValue;
}
}
You either assume that instantiating (new) a Form magically shows it or gets a reference to an existing open form. None of those assumptions is true.
To show a form to the user you either call Application.Run for your first form (the main form of your application) or Show
or ShowDialog on a instance you created.
Let me add comments to the first few lines of your ReadTable method:
TestForm t = new TestForm(); // this ONLY creates a NEW form in memory
// if you were looking at a TestForm already t holds a new form
// and not the one you're looking at.
var returnValue = new DataTable();
var conn = new SqlConnection(ConnectionString._connectionString);
// the form is not shown to the user at this point
// and never will be because YOU didn't tell it to Show
// The textbox is empty
string st = t.sql1.Text;
// st will be an empty string here
With that explained let's see possible solutions. You might be tempted to add
t.Show();
directly after you created the TestForm. That does show the form but Show is non-blocking. Which means it will continue immediately with the rest of the code still leading to an empty result in st.
t.ShowDialog();
will enable you to see the form and fill in any values. ShowDialog will block until the users closes the form or you have a button that calls Close or Hide in the click event.
Based on the sparse information you provided I assume you already have TestForm open, with a button on it that calls ReadTable. If you change ReadTable to accept a the sql string, you don't have to juggle with the forms.
Something like this will do:
public class ProcessDataset
{
// Takes a Sql string
public static DataTable ReadTable(string sql)
{
var returnValue = new DataTable();
// checks if there is a sql string provided
if (!String.IsNullOrEmpty(sql))
{
var conn = new SqlConnection(ConnectionString._connectionString);
conn.Open();
var command = new SqlCommand(sql, conn);
// rest of code
}
else
{
// show message to user
MessageBox.Show(" no sql command ");
}
return returnValue;
}
}
And you will call it from your click event like so:
private void button2_Click(object sender, EventArgs e)
{
var resultset = ProcessDataset.ReadTable(sql1.Text);
}
tl;dr There is not much wrong with your SqlCommand code. You simply failed in getting the correct reference to your Textbox that contains some sql statement. Calling sqlcommand with an empty string raises the exception you are seeing.
I'm extremely new to C# and programming anything except for SQL. I've gotten the below code to happen on a Form and on a button click. If I wanted to just make this run on open, how would I do that? I'm very new to C# as you can tell (just started today learning it but its pretty exciting!)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace OraTrigger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT cast(Count(*) as varchar(20)) as trig FROM ZDMSN.TRIGGER_TEST";
//cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
int cnt;
if (int.TryParse(dr.GetString(0), out cnt))
{
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
}
}
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
conn.Dispose();
}
}
}
If you need to run your code as a scheduled task then a command line application is more suitable.
Just create a new project and select Console Application.
Then move all of your button click code inside the Main method written for you by the Visual Studio IDE.
Rembember to set the references to the Oracle ODP.NET library and import the relevant using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand("SELECT Count(*) as trig FROM ZDMSN.TRIGGER_TEST", conn))
{
conn.Open();
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
cmd.ExecuteNonQuery();
}
}
}
}
}
I have also revised your code to get a single value from the database. For this case is enough to use the Command.ExecuteScalar method that returns the first column of the first row obtained from your sql command text. Because the count(*) should Always return a single row you could easily cast the return value of ExecuteScalar to your record count variable.
EDIT I have added the logic to TRUNCATE the table involved. Please pay attention that you should use the code provided here. Your code will probably fail because you have an open DataReader and when a DataReader is open you cannot execute other commands (This is true for SqlServer without Multiple Active Result Sets enabled, I really don't know if this rules applies also to the Oracle NET Provider)
Subscribe to Shown or Load event of form and move your code to that event handler.
Form.Shown Event Occurs whenever the form is first displayed.
Form.Load Event Occurs before a form is displayed for the first time.
Also I suggest to extract your code to some Data Access related class, or at least to separate method. And call that method from event handler.
I am developing a simple domain application using web services.I got the domain information using whois wsdl.That is working well but I am getting the entire data the problem is I need only selected data from that server like domain name, creation date,expire date.
In my design I made two text box when entered any domain name in textbox1 if it is exist in whois server it must show selective information into textbox2.
I tried to store these values in a text file and save its name in db but its not working for me. Any ideas friends
Here is my coding
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class do01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string st = TextBox1.Text;
wservices.whois myservices = new wservices.whois();
TextBox2.Text = myservices.GetWhoIS(st);
}
}
Here is my screenshot
If you have any ideas just shoot it here friends.... :)
NOTE: See update below for a change of answer
I'm assuming that what you want is to have a table with this information as the plain text in a column.
A basic table definition
CREATE TABLE WhoIsData
(
Id INT PRIMARY KEY IDENTITY(1,1),
WhoIsData NVARCHAR(MAX)
)
I don't know what st is (which is the data you send to the service, it may be useful in your table if you also want to store that too).
C# code (roughly - I've not tested it)
string st = TextBox1.Text;
wservices.whois myservices = new wservices.whois();
string textData = myservices.GetWhoIS(st);
TextBox2.Text = textData;
using(SqlConnection conn = new SqlConnection(connectionString));
{
SqlCommand cmd = new SqlCommand("INSERT INTO WhoIsData(WhoIsData) VALUES(#text);");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#text", textData);
conn.Open();
cmd.ExecuteNonQuery();
}
I'd separate out the SQL Calls from your user interface classes in real life. But for the sake of the example I've put it all together. Also, I've not renamed your text boxes, although TextBox1 and TextBox2 are really bad names.
UPDATE
Okay - You want to store the content in a text file, but I'm assuming you want to store a link to the text file in the database (you've not been very specific)
The Table definition:
CREATE TABLE WhoIsData
(
Id INT PRIMARY KEY IDENTITY(1,1),
DomainName NVARCHAR(256),
WhoIsFile NVARCHAR(256)
)
The C# code:
string st = TextBox1.Text;
wservices.whois myservices = new wservices.whois();
string textData = myservices.GetWhoIS(st);
TextBox2.Text = textData;
string fileName = Guid.NewGuid().ToString();
using(var file = File.OpenWrite(fileName))
{
file.Write(textData);
}
using(SqlConnection conn = new SqlConnection(connectionString));
{
SqlCommand cmd = new SqlCommand("INSERT INTO WhoIsData(DomainName, WhoIsFile) VALUES(#domainName, #fileName);");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.Parameters.AddWithValue("#domainName", domainName);
conn.Open();
cmd.ExecuteNonQuery();
}
Again, I've not tested this, but it is roughly what you want to do. Also, you need to provide a mechanism for generating the file name, I've just used a guid as it pretty much guarantees uniqueness.