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;
}
Related
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.
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.
I use a button to save textbox en dropdown valves to a database
but the problem is its for a reservation system for my cousin and he has a maximum of 50 seats.
My question is can i put in some kind of validation or count that give back a massage when the
maxiumum places is reached or surpased to the one that wants to make a reservation.
here is my button
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BT-1ConnectionString"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from OpdrachtGever";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "OpdrachtGever");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
drow["Naam"] = TextBox1.Text;
drow["Adres"] = TextBox2.Text;
drow["PostCode"] = TextBox3.Text;
drow["WoonPlaats"] = TextBox4.Text;
drow["TelefoonNummer"] = TextBox5.Text;
drow["EmailAdres"] = TextBox6.Text;
drow["AantalPersonen"] = DropDownList1.SelectedValue;
ds.Tables["OpdrachtGever"].Rows.Add(drow);
da.Update(ds, "OpdrachtGever");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
}
}
}
You could check the number of rows in the OpdrachtGever table after filling the dataset:
da.Fill(ds, "OpdrachtGever");
// Check booked count
int totalBooked = 0;
foreach (DataRow row in ds.Tables["OpdrachtGever"].Rows)
{
totalBooked += Int32.Parse(row["AantalPersonen"]);
}
if (totalBooked >= 50)
{
//show error and return
}
I've looked through the other questions related to this, but I'm having a different issue. I can't get a specific item to return, it only returns my column name. How do I get the item to return?
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT #FieldName FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
I've also tried
return ds.Tables[0].Rows[0][0].ToString();
I'm just getting whatever is in the field variable.
If I pass in ("CompanyName", 33), it returns "CompanyName".
Your query (in sql profiler) is
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
So it returns exactly "CompanyName" string. You cannot pass column name as sqlparameter. You should do something like
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = #CompanyNum", field);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
But this code can be used for SQL injection.
To avoid Sql injection, you could check that fieldName in field variable is one of the table columns.
Or You could get SELECT * FROM Сompanies WHERE СompanyNum = #CompanyNum and get value of named column from datatable:
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT * FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0][field].ToString();
}
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);
}
}
}