How can I fill a GridView in foreach because this code bring last row just not all.
foreach (int i in userdetails)
{
SqlConnection con = new SqlConnection("*****");
SqlCommand cmd = new SqlCommand("********=" + i, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvSelected.Visible = true;
gvSelected.DataSource = ds;
gvSelected.DataBind();
}
You will want to do something more like this. Only get the data in the loop.
Notice I also used a SqlParameter which is important to prevent SQL Injection and avoid syntax errors.
SqlConnection con = new SqlConnection("*****");
SqlCommand cmd = new SqlCommand("********=#id", con);
SqlParameter parId = new SqlParameter("#id", SqlDbType.Int);
cmd.Parameters.Add(parId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
foreach (int i in userdetails)
{
parId.Value = i;
da.Fill(ds);
}
gvSelected.Visible = true;
gvSelected.DataSource = ds;
gvSelected.DataBind();
Of course you should consider trying to send all ids at once if possible. You would need something like a Table Valued parameter for that.
Related
I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.
the problem is i can use my database if my gridview is not connected to database using sqldatasource
it will work if my database is connected manually using code to gridview
i need a code to search my data using datagrid and textbox and button with the search code in it
here's my current code for search command
but its only working when i connect my datagrid to database manually using code
strconn = "select * from User_TBL_DB where (Lastname like '%' + #search +'%')";
SqlCommand xp = new SqlCommand(strconn, conn);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = SearchBOX.Text;
conn.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView2.DataSource = ds;
GridView2.DataBind();
conn.Close();
hope you can help me
SQL Command is not correct. It should be ... LIKE '%#Search%'
var ds = new DataSet();
using (var cnn = new SqlConnection(CONNECTION_STRING))
{
string cmdText = "SELECT * FROM User_TBL_DB WHERE Lastname LIKE '%#Search%'";
var cmd = new SqlCommand(cmdText, cnn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Search", SearchBOX.Text);
cnn.Open();
var da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "Name");
}
GridView2.DataSource = ds;
GridView2.DataBind();
how am i going prevent "lesson Title" from duplicating in database when user input duplicate data?
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
That kind of uniqueness should be enforced by the database. Add a unique constraint to your table:
CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
You can create a function to check the duplicate LessonTitle.
Explanantion: here i have created a function called checkDuplicateTitle().
this function takes AllRows of a LessonTable as DataRowCollection and LessonTitle to be verified as inputs.
it will check the LessonTitle of each and every row.
if given LessonTitle is matched with existing Titles from Table then this function returns true else returns false.
if the returned value is true we will ignore the updating the table with new row as LessonTitle is already Existing otherwise we will add it.
Code as below:
void UpdateLessonTable()
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
{
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
}
else
{
//you can display some warning here
// MessageBox.Show("Duplicate Lesson Title!");
}
}
//function for checking duplicate LessonTitle
bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
{
foreach (DataRow row in rowTitle)
{
if(row["LessonTitle"].Equals(newTitle))
return true;
}
return false;
}
I have the following C# code:
public string TargetDate()
{
SqlConnection con =
new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
SqlCommand cmd = new SqlCommand("select * from Timer");
con.Open();
DataSet ds = new DataSet(cmd,con);
SqlDataAdapter da = new SqlDataAdapter();
da.Fill(ds);
con.Close();
}
but I get error at the: new DataSet(cmd,con); ...
the error: CS1502: The best overloaded
method match for
'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,
System.Runtime.Serialization.StreamingContext)'
has some invalid arguments
What is could be the problem?
Try this:
SqlConnection con = new SqlConnection
("Server=localhost;Database=Timer;Trusted_Connection=True");
SqlCommand cmd = new SqlCommand("select * from Timer", con);
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
This is even better:
DataTable dataTable = new DataTable();
using(SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
using(SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from Timer";
connection.Open();
SqlDataReader reader = command.ExecuteReader();
dataTable.Load(reader);
}
You've got the wrong constructor for the DataSet. Try this
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);
It seems you have mixed up the constructors:
Try the following:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);
Hope that helps
I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable
body of procedure
select * from table
end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}