Hie I'm new to ASP.Net and needed some help.
Here is my problem: I have 4 drop downs in my application, a button saying search, grid view to show the results. I was trying to filter the results based on the value of drop downs.
So i wrote the query as "select * from table where column1=dd1.SelectedItem.Value" but the tricky part is i want the results to be displayed even if one of the drop down is selected or two of them is selected or all of them is selected. How do i write the Where Part in my SQL query?? I know that I have to use dynamic SQL but i have no clue about dynamic SQL.
Use something like this
string q = #"
SELECT * FROM table
WHERE
(#value1 IS NULL OR column1 = #value1)
AND
(#value2 IS NULL OR column2 = #value2)
AND
(#value3 IS NULL OR column3 = #value3)
";
var command = new SqlCommand();
command.CommandText = q;
command.Parameters.AddWithValue("#value1", dd1.SelectedItem.Value);
command.Parameters.AddWithValue("#value2", dd2.SelectedItem.Value);
command.Parameters.AddWithValue("#value3", dd3.SelectedItem.Value);
First you should store dd1.SelectedItem.Value in a variable as
string v = dd1.SelectedItem.Value.ToString();
then create a string for your query as
string q = "select * from table where (column1 is null or column1=" + v + ")";
then use this code:
SqlCommand com = new SqlCommand(q, yoursqlconnection);
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
Related
I want to select data from Microsoft SQL Server and concatenate two of its column values and display it in ListBox.
For example - there are two columns in SQL, namely Software name and Software-users. A single software has N number of users what I want to do is select the software name in SQL and concatenate it with Software users name and display it in the listbox.
So far I tried this, but the listbox displays null.
SqlCommand cmd = new SqlCommand("Select [SWName] +'-'+ [SWUser] as Creator from AllSWUsers WHERE SWName = #SWName", con);
cmd.Parameters.AddWithValue("#SWName", Global.usrlsts);
SqlDataAdapter daFill = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
daFill.Fill(ds);
lstUsers.DataSource = ds;
lstUsers.DataTextField = "Creator";
lstUsers.DataValueField = "SWName";
lstUsers.DataBind();
It may be the reason you are not selecting SWName in your query but you are using that column as shown below in your code.
lstUsers.DataValueField = "SWName";
Try this
Select ISNULL([SWName], '') as [SWName], ISNULL([SWName],'') +'-'+ ISNULL([SWUser], '') as Creator from AllSWUsers WHERE SWName = #SWName
I need to populate a datagrid with the following columns.
invnumber,itemname,rate,quantity..
itemname,rate,quantity comes from 1 table while invnumber comes from another table
I used to do like this
string commandText = "SELECT invnumber,cname,date FROM inv_table WHERE invnumber LIKE #id";
SqlCommand command = new SqlCommand(commandText, conn);
string searchParam = String.Format("%{0}%", text_inv.Text);
command.Parameters.AddWithValue("#id", searchParam);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
Now i cannot directly assign the data source as 2 different tables are involved
dataGridView2.DataSource = dt;
How can i get around this.
To emit combined result from 2 or more different tables in a table, use either INNER JOIN, LEFT JOIN, RIGHT JOIN or UNION statement depending on your need.
In this case, you need to join first table and other table to get desired results, assume invnumber is unique or primary key. Here is an example:
string commandText = "SELECT other.invnumber, inv.cname, inv.date FROM inv_table AS inv
INNER JOIN other_table AS other
ON inv.invnumber = other.invnumber
WHERE other.invnumber LIKE #id";
Or if you have already defined classes for each table, use LINQ to SQL with lambda expression:
DataContext dc = new DataContext();
var results = dc.InvTable.Join(OtherTable, inv => inv.invnumber, other => other.invnumber, (inv, other) => new { invnumber = other.invnumber, cname = inv.cname, date = inv.date });
Any improvements and suggestions welcome.
Create a new class for the data structure of the 2 different table, populate the new one and use. (easier and the most clear solution)
Problem:
Code works fine, however, when I launch my program my two predefined columns Course_ID and File_Count are present in my then blank dataGridView. There is also an empty default row.
Whenever I run my query, my dataGridView is getting an extra column created and an extra row created. The result from the query goes into this new third column on the first row which is weird.
See here:
http://imgur.com/UBFI8Nz
Here is my code:
string[] courses = txtBoxCourses.Text.Split(',');
SqlConnection myConnection = new SqlConnection("user id=userid;" +
"password=password;server=myserver;" +
"Trusted_Connection=no;" +
"connection timeout=30");
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
myCommand.Connection = myConnection;
DataTable t = new DataTable();
foreach (string line in courses)
{
myCommand.CommandText = "DECLARE #CourseName varchar(80); Set #CourseName = '"+line+"' SELECT COUNT(*) FROM ( SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;";
adapter.Fill(t);
dataGridView1.DataSource = t;
}
What I want to happen is I want to fill in the first column with the values from my string[] courses list and I want it to correspond with the result from the query in my foreach statement. For example, if I use two course IDs to query, test1 and test2 I'd prefer this:
Course_ID file_count
test1 234
test2 1478
I've looked into using the DataPropertyName property but I don't think that's it.
Try changing your select to:
SELECT #CourseName as Course_ID, COUNT(*) as File_Count FROM (
SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS
WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;
Your current query is returning an integer and your grid view doesn't see it attached to any of your predefined columns. Try aliasing the columns with the column name in the grid view. That should tie your sql results to your current columns.
I have codes here that display all data in access database. Is it possible to only display specific or selected data from my database?
here is my code :
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\SISC-STRONGHOLD\MIS!\wilbert.beltran\SEEDBucksDbase.accdb";
string query = "SELECT * From TableAcct";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns["UserPassword"].Visible = false;
}
conn.Close();
}
thanks! :)
To query for a last name (assuming the column in the table is called LastName), try this:
string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";
Of course, you have to be careful of SQL Injection attacks. I'm not familiar with using paramaterized queries in Access.
Is this a public form, or internal just for you (or trusted users)?
you just need to write down where condition in you query will do work for you,
Following is example of it
string query = "SELECT col1,col2 From TableAcct where col1=value";
This will fetch data that satisfy you condition and bind with the grid control.
And instead of * in select list give name of the columns you want to display.
for getting value form control like textbox
string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";
Note- make use of sqlparameter to avoid SQLInjection , above is just an example.
string query = "SELECT (SelectedColumnNames) From TableAcct Where LastName=(LastName)";
INstead of Searching with a * in a Query enter the desired columns for ex:-
string query = "SELECT phno,address,FirstName From TableAcct where LastName ='"+txt1.text +"'";
I am using sqlconnection. I want to create a view and select from the view set.
Like I have shown below I have created a view called vwtopic.. from this I need to select distinct values of a column.
I cannot put in one easy statment because i need distinct values of topic column only and need to order by another column datetime..
So I am first creating a view where I am ordering by datetime and from this I am selecting distinct topic.
Problem is I am able to create a view set, but from this I am not able to select the distinct topic data to a SqlDataAdapter.. I frankly dont know the syntax.. I have not tried this before..
First part:
SqlConnection con = new SqlConnection("server=xxxx;database=wbsd;user id=***;password=***;");
SqlCommand add = new SqlCommand("CREATE VIEW vwtopic AS SELECT * FROM sr_topic_comment ORDER BY datetime DESC", con);
try
{
add.Connection.Open();
add.ExecuteNonQuery();
add.Connection.Close();
}
catch (System.FormatException)
{
}
Second part:
String sqlcmd = "SELECT DISTINCT topic FROM vwtopic WHERE owner='" + owner + "'";
SqlDataAdapter adap = new SqlDataAdapter(sqlcmd,con);
Instead of creating Views in Code, use the "WITH" statement or Sub-queries this should meets your needs:
WITH [vwtopic] AS (
SELECT * -- I recommend using each column name
FROM [sr_topic_comment]
-- not sure if ORDER BY is allowed here:
-- ORDER BY [datetime] DESC
)
SELECT DISTINCT [topic] FROM [vwtopic] -- add WHERE, ORDER BY
Since the view you are creating does not have any filters defined, selecting distinct values from the view is equivalent to selecting distinct values from the table. When selecting distinct values, you can only order by those values (not the datetime column as you're attempting here). Therefore, you can do:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT topic FROM sr_topic_comment WHERE owner = #owner", con);
cmd.Parameters.Add(new SqlParameter(#owner, SqlDbType.Varchar, 25));
cmd.Parameters["#owner"].Value = owner;
DataSet ds = new DataSet();
using (SqlDataAdapter adap = new SqlDataAdapter(cmd)) {
adap.Fill(ds);
}
This will give you a DataSet filled with the distinct values from the table that meet the filter criteria (owner == the supplied owner).
I found the answer below will do the trick for me...
I am filling the result in dataset and calling my required column 'topic'..
SELECT DISTINCT topic,datetime FROM sr_topic_comment WHERE owner='sr' ORDER BY datetime DESC
Thank you very much for your inputs.. I learnt about WITH clause today.. cheers..