Reputation: 167
The following code is used by me to load a set of items in sqlite database to a datagrid view upon a button click! When the path to the database is given as in the code the database is successfully connected and data is loaded.
public Form1()
{
InitializeComponent();
dbconnection = @" Data Source = D:\SQLite\SQLiteStudio\DB1.db ; version=3 ";
}
but when i change the code as follows by obtaining the path as textbox input an error "Data source can not be empty" occurs. The name of the textbox used is dbtext and the same path in the above code is copied and pasted to the text box!
public Form1()
{
InitializeComponent();
dbconnection = @"Data Source="+dbtext.Text+";version=3";
}
How can i correct this issue?
Upvotes: 1
Views: 736
Reputation: 3407
You are setting the connection string in the constructor of your program:
public Form1()
{
InitializeComponent();
dbconnection = @"Data Source="+dbtext.Text+";version=3";
}
At this point the TextBox
is still empty and the variable dbconnection
will look like this:
dbconnection = "DataSource=;version=3";
(check it in the debugger).
Now you are trying to establish a connection on your button click event, but to where? Instead, your code should look like this:
priavte void Button1_Click(object sender, EventArgs e)
{
dbconnection = "Data Source="+dbtext.Text+";version=3";
//Do stuff with the connection
}
Upvotes: 1
Reputation: 34150
The problem is that you are setting it on form initialization where textbox is still empty and you set its value.
set dbconnection = @"Data Source="+dbtext.Text+";version=3";
on Click event of the same button that loads the data or on textchanged event of the textbox.
Upvotes: 2