i have the code of passing a selected value in the the query and that value will bind the data in the girdview. the selection is made with the Listbox..
I want to pass a list param of S_ID
Now I want to modify my program a little i want to pass a list of param. in the query.. so that this can enable multiple selection list in the listbox.. I've searched over Internet and i couldnt find a certain satisfying answer... I'm not very good at query.
protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database11.accdb";
con.Open();
for (int i = 0; i < ListBox1.Items.Count; i++)
//foreach(Items Item in Listbox1)
{
if (ListBox1.Items[i].Selected == true)
{
string Skill_ID = ListBox1.Items[i].Value;
string query1 = "SELECT *FROM Emp AS E, Junction AS J WHERE E.E_ID=J.E_ID And J.S_ID=#Skill_ID";
OleDbCommand cmd1 = new OleDbCommand(query1, con);
cmd1.Parameters.AddWithValue("#Skill_ID", Skill_ID);
OleDbDataReader rs = cmd1.ExecuteReader();
if (rs.HasRows)
{
GridView1.DataSource = rs;
GridView1.DataBind();
rs.Close();
}
//use LINQ to obtain the selected id values as strings
var selectedItems = ListBox1.Items.Cast<ListItem>().Where(p => p.Selected == true).Select(p => p.Value).ToList();
//now concat them as a comma seperated string
var idCommaList = string.Join(', ', selectedItems);
//Now use a WHERE IN () statement instead with your query and concat your comma seperated list of ids into the sql statement
var query1 = #"SELECT *
FROM Emp AS E, Junction AS J
WHERE E.E_ID = J.E_ID AND J.S_ID IN (" + idCommaList + ")";
Related
I have three SQL Tables - Team (Id, Name), Player (Id, Name) and TeamPlayer (Id, TeamID, PlayerID). I also have two ListBoxes on my Form and want to filter the 2nd ListBox when an Item is selected on the 1st ListBox.
This is mostly setup but I'm having issues where the code is not liking the value being passed to it in the LstTeams_SelectedIndexChanged method at the commented lines.
private void Form1_Load(object sender, System.EventArgs e)
{
showTeams();
}
private void showTeams()
{
// Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
string query = "select * from Team";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
// Get the 'Team' Table and Fill it
DataTable teamTable = new DataTable();
sqlDataAdapter.Fill(teamTable);
// Populate the 'Team' ListBox with the 'Team' Table
lstTeams.DataSource = teamTable.DefaultView;
lstTeams.DisplayMember = "Name";
lstTeams.ValueMember = "Id";
}
private void LstTeams_SelectedIndexChanged(object sender, System.EventArgs e)
{
string TeamID = lstTeams.GetItemText(lstTeams.SelectedValue);
MessageBox.Show("TeamID: " + TeamID);
// Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = #TeamID";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.Parameters.AddWithValue("#TeamID", lstTeams.SelectedValue); // this
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); // causes the dataadapter to error
// Get the 'Team' Table and Fill it
DataTable teamTable = new DataTable();
sqlDataAdapter.Fill(teamTable);
// Populate the 'Team' ListBox with the 'Team' Table
lstPlayers.DataSource = teamTable.DefaultView;
lstPlayers.DisplayMember = "Name";
}
My Error is:
System.ArgumentException: 'No mapping exists from object type System.Data.DataRowView to a known managed provider native type.'
I've looked up some solutions but have been unable to get a working result.
Thank you for any help provided :).
After further research and some direction from comments made to my question, I have found success with the following:
DataRowView data = lstTeams.SelectedItem as DataRowView;
int TeamID = int.Parse(data["Id"].ToString());
string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = " + TeamID;
Inside the ListBox1.SelectedIndexChanged method.
I am attempting to fill a datatable with the following query:
SELECT
recipes.Name, Instructions, recipes.Preperation_Time, Author
FROM
RecipeIngredients
INNER JOIN
recipes ON recipes.Recipe_ID = RecipeIngredients.Recipe_ID
INNER JOIN
Ingredients ON Ingredients.Ingredient_ID = RecipeIngredients.Ingredient_ID
WHERE
ingredients.Name IN ('eggs')
When I run this query inside an .sql file I get the desired results:
However, when I attempt to fill a datatable with the query, I do not get any results. This is not an issue with my database nor the code as when I use a simple query, such as:
"Select * FROM recipes"
I get all recipes inside my datagridview:
Am I missing something here?
Here is my code for the form and the Database connections class.
private void resultsWindow_Load(object sender, EventArgs e)
{
// Format ingredient array for SQL Syntax
for(int i = 0; i< ingredientCount; i++)
{
string ing = ingredientArray[i];
string editedIng = "'" + ing + "'";
ingredientArray[i] = editedIng;
}
string ingredientString = string.Join(", ", ingredientArray);
// get connection string
string connectionString = Properties.Settings.Default.ConnectionString;
DataTable recipeDataTable = new DataTable();
conn = new DatabaseConnections(connectionString);
conn.openConnection();
// Get datatable
recipeDataTable = conn.getRecipes(ingredientString);
// Display data in grid view
recipesDataGrid.DataSource = recipeDataTable;
recipesDataGrid.Refresh();
}
public DataTable getRecipes(string ingredientString)
{
string sqlString = ("SELECT recipes.Name, Instructions, recipes.Preperation_Time, Author FROM RecipeIngredients" +
" INNER JOIN recipes ON recipes.Recipe_ID = RecipeIngredients.Recipe_ID" +
" INNER JOIN Ingredients ON Ingredients.Ingredient_ID = RecipeIngredients.Ingredient_ID" +
" WHERE ingredients.Name IN ('eggs')");
string sqlString_ = ("Select * FROM recipes");
DataTable recipeDataTable = new DataTable();
openConnection();
SqlCommand cmd = new SqlCommand(sqlString_, connectionToDB);
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Fill dataset
da.Fill(recipeDataTable);
closeConnection();
return recipeDataTable;
}
I didn't try your code, but probably you just added the data in the table and it's not yet validated.
Could you try this statement in your T-SQL editor:
COMMIT TRANSACTION;
I'm a newbie when it comes to C#, but have some experience with C, Python and MATLAB. I wrote a simple C# program that takes in some user input and converts it into a (parameterized) SQL query. I've successfully converted the datetimepicker into a SQL query; however, I have another parameter (serial numbers) that the user would input into a textbox. They can enter multiple serial numbers, separated by commas. Once the user clicks on 'Submit', the SQL query is sent and the results displayed in a dataGridView.
It works with a single value (i.e. a single serial number), but when I try to put in multiple values, it doesn't work.
I've tried some suggestions like separating the textbox string into an array of values.
private DataTable GetResults()
{
DataTable dtResults = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = con.CreateCommand())
{
string[] numbers = textBox2.Text.Split(',');
var parameters = new string[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
parameters[i] = string.Format("#SN{0}", i);
cmd.Parameters.AddWithValue(parameters[i], numbers[i]);
}
cmd.CommandText = string.Format("SELECT [TestDate],[ParamName],[SerialNumber],[TestDataID],[MeasuredValue]," +
"[MaximumLimit],[MinimumLimit],[PassResult] FROM [dbo].[Device.ParametricTestResults] " +
"WHERE SerialNumber IN ({0}) " +
"AND (TestDate BETWEEN (#start) AND (#end)) " +
"AND PassResult = 1", string.Join(", ", parameters));
cmd.Parameters.AddWithValue("#start", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#end", dateTimePicker2.Text);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtResults.Load(reader);
}
}
return dtResults;
}
And the 'Submit' button has the following code attached to it:
private void button12_Click(object sender, EventArgs e)
{
TestResultsdataGridView.DataSource = GetResults();
}
Again, the datagridview should display entries for multiple serial numbers, but it only works for one.
I have two checkbox lists, one for a division and one for a course. One division can have many courses so what I want to do is have my user select whichever divisions they want as there are only 10 then display the courses in another checkbox list which are offered by the divisions that have been selected.
Precursor info:
private DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
This is my code where I bind the data to the Divisions checkbox list:
protected void GetDiv()
{
string query = " Select distinct uio.OFFERING_ORGANISATION as [Div], ou.FES_FULL_NAME as [Division] From UNIT_INSTANCE_OCCURRENCES uio " +
" inner join ORGANISATION_UNITS ou on uio.OFFERING_ORGANISATION = ou.ORGANISATION_CODE " +
" inner join REPORTYEARS ry on uio.CALOCC_OCCURRENCE_CODE = ry.CAL_OCC " +
" Where ry.REPORT_YEAR = (select DETAILS from EF_REFERENCE_DATA Where REC_TYPE = 'Rep_Year') and uio.OFFERING_ORGANISATION is not null Order By [Division] ";
cbDivSelect.DataSource = GetData(query);
cbDivSelect.DataTextField = "DIVISION";
cbDivSelect.DataValueField = "DIV";
cbDivSelect.DataBind();
}
I use this to get a list of the divisions selected:
protected void cbDivSelect_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem item in cbDivSelect.Items)
{
if (item.Selected) Divisions.Add(item);
}
}
and then this to display the Courses:
protected void GetCourse()
{
foreach(ListItem item in Divisions)
{
string GetCourses = "SELECT distinct Course_Code,Course_Code + ' - ' + Marketing_Title AS COURSE, Parent FROM e_prospectus WHERE (Div = '" + item.Value.ToString() + "') ORDER BY Course_Code";
cbCourseSelect.DataSource = GetData(GetCourses);
cbCourseSelect.DataTextField = "COURSE";
cbCourseSelect.DataValueField = "Course_Code";
cbCourseSelect.DataBind();
}
}
Now currently it only displays the lowest course in the list which has been selected, i'm assuming because i keep changing the data source and it doesn't accumulate but is there any way i can change my code to accommodate what i want? thanks
Create one DataTable as DataSource and Merge() the results of GetData() into it.
This would build the whole set in memory. Depending how many Courses you expect using FakeisMe approach of building one query to get all courses out of the database at once might be a lot faster.
string divisions = string.empty ;
foreach(ListItem item in Divisions)
{
divisions = divisions + item.Value.tostring() + ",";
}
if (divisions != string.empty)
{
divisions = divisions.Remove(divisions.Length -1, 1)
string GetCourses = "SELECT distinct Course_Code,Course_Code + ' - ' + Marketing_Title AS COURSE, Parent FROM e_prospectus
WHERE (Div in (" + divisions + ")) ORDER BY Course_Code";
cbCourseSelect.DataSource = GetData(GetCourses);
cbCourseSelect.DataTextField = "COURSE";
cbCourseSelect.DataValueField = "Course_Code";
cbCourseSelect.DataBind();
}
I want to select file contains .txt and split all strings in each text into array
then insert the divided words into sql database (word, counter) and count the repeated words in each text by counter that lead to unrepeated words in database tables>>
(1)-counter code is incorrect I found several errors in my code >> (i want to prevent a repeat of word at the same time calculate how many times repeated word in databases ,by using counter.)
(2)- my code has static path (just one text ),but I want user to select his file which he want to split. (browse.. button)
(3-)sql database could not show Arabic Words (?????)
namespace lib123
{
public partial class Form1 : Form
{
SqlConnection sqlConn;
SqlCommand sqlComm;
SqlDataAdapter sqlAdptr;
public Form1()
{
InitializeComponent();
sqlConn = new SqlConnection();
sqlComm = new SqlCommand();
sqlAdptr = new SqlDataAdapter();
sqlComm.Connection = sqlConn;
sqlComm.CommandType = CommandType.Text;
sqlConn.ConnectionString = "Data Source=007-PC\\SQLEXPRESS ;Initial Catalog= Email_DB;Integrated Security =True ";
}
private void Form1_Load(object sender, EventArgs e)
{
FillGrid();
}
private void button1_Click(object sender, EventArgs e)
{
if (sqlConn.State != ConnectionState.Open)
sqlConn.Open();
// sqlComm = sqlConn.CreateCommand();
StreamReader streamReader = new StreamReader(#"C:\Users\007\Desktop\spam-email\spamenglish.txt"); //get the file
string stringWithMultipleSpaces = streamReader.ReadToEnd(); //load file to string
streamReader.Close();
Regex r = new Regex(" +"); //specify delimiter (spaces)
string[] words = r.Split(stringWithMultipleSpaces); //(convert string to array of words)
int c = 1;
string strQry = "select ISNULL( max(id),0) as id from word_tb ";
sqlComm.CommandText = strQry;
int LastID = int.Parse(sqlComm.ExecuteScalar().ToString());
string x ;
String st = null;
for (int i = 0; i < words.Length; i++)
{
string y = words[i];
for (int j = 0; j <LastID; j++)
{
x = "select word from word_tb where id = j";
sqlComm.CommandText = x ;
if (x.Equals(y))
{
c = c + 1;
string sql = "INSERT INTO word_tb (count) VALUES ('" + c + "') where id = i";
sqlComm.CommandText = sql;
}
else
{
LastID = LastID + 1;
st += "INSERT INTO word_tb(id, word,count) VALUES('" + LastID + "', '" + words[i].ToString() + "','" + c + "');";
//st += "INSERT INTO word_tb(word) VALUES('" + words[i].ToString() + "');";
}
}
}
sqlComm.CommandType = CommandType.Text;
sqlComm.CommandText = st;
sqlComm.ExecuteNonQuery();
FillGrid();
}
private void FillGrid()
{
DataTable tbl = new DataTable();
string strQry = "select * from word_tb ";
sqlComm.CommandText = strQry;
sqlAdptr.SelectCommand = sqlComm;
sqlAdptr.Fill (tbl) ;
dataGridView1.DataSource = tbl;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
//private void btnDelete_Click(object sender, EventArgs e)
//{
// string str = "DELETE FROM word_tb";
// sqlComm.CommandType = CommandType.Text;
// sqlComm.CommandText = str;
// sqlComm.ExecuteNonQuery();
// dataGridView1.Rows.Clear();
// }
}
}
1-counter code is incorrect I found several errors in my code?
you can use below code to split the File Text into words based on space as delimiter.
Code:
String strAllData = System.IO.File.ReadAllText(#"C:\Users\007\Desktop\spam-email\spamenglish.txt");
String[] words = strAllData.Split(' ');
2- my code has static path (just one text ),but I want user to select
his file which he want to split. (browse.. button) ?
you can use OpenFileDialog control to let user choose the file which he/she wants to work on.
Code:
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
String strAllData = System.IO.File.ReadAllText(fileDialog.FileName);
String[] words = strAllData.Split(' ');
}
3 -sql database could not show Arabic Words (?????) ?
Sql Server can not show Uni Code characters when you fire a SELECT Query because you have created your table columns/feilds as varchar.
Solution: if you want to get the Arabic characters when you fire a SELECT query you should create your table columns to accept Uni Code characters using NVARCHAR datatype instead of VARCHAR. N stands for National language character set.
Step1 : create your table columns as NVARCHAR as below:
create table sample(
[name] [nvarchar](100) NOT NULL)
Step 2: Use N as prefix while inserting Data into NVARCHAR columns. N as prefix tells that all following characters are Uni Code characters.
Code:
INSERT INTO sample VALUES(N'لا أتكلم العربية');
Now if you fire a SELECT Query you will be able to see the Arabic Characters.