Reputation: 9551
I ran the SQL Query in SQL Server Management Studio and it worked.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
dataGridView1.DataSource = GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
dataGridView1.DataSource = GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "@word" + (i++).ToString();
command.Parameters.AddWithValue(name, "'%" + word "%'");
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
No error is given by VS2012 and no data is presented in my DataGridView
Any suggestions?
I saw this website and it didn't really help
http://bytes.com/topic/c-sharp/answers/530616-datagridview-combobox-column-databound-item-list
I am using an SQL Server 2012
The updated Query brings 1 single result in the SQL Server Management Studio (which is expected). The same query does not produce any rows in my datagrid.
I can't figure out whats going on? Do I need to bind anything using the GUI for VS2012?
Upvotes: 0
Views: 3086
Reputation: 62861
I notice you're doing a LIKE search, but when you're adding your parameters, you're not using "%". Try adding this:
command.Parameters.AddWithValue(name, "%" + word +"%");
Hope this helps.
BTW -- The DataBind
method is not used in win forms for gridviews, just in web forms.
Good luck.
Upvotes: 4
Reputation: 388
You should call method DataBind() on your DataGrid to actually bind data from the data source to the grid.
dataGridView1.DataBind();
Upvotes: 1