void LoadData()
{
DataTable dtshow = new DataTable();
DataTable dt = new DataTable();
if (con.State == ConnectionState.Closed)
{
con.Open();
}
//query get data show in grid
SqlCommand cmdshow = new SqlCommand("SELECT a,b,c FROM XXX", con);
//query check database change
SqlCommand cmd = new SqlCommand("SELECT a,b,c FROM XXX", con);
cmd.Notification = null;
SqlDependency de = new SqlDependency(cmd);
de.OnChange += new OnChangeEventHandler(de_OnChange);
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
if (con.State == ConnectionState.Closed)
{
con.Open();
}
dtshow.Load(cmdshow.ExecuteReader(CommandBehavior.CloseConnection));
dataGridView1.DataSource = dtshow;
}
Hi, all my code is above,
When I update "a" column from the specific row, I need to find "b" and "c" from that row.
How can I get that ??
Thanks
Im not sure what SQL you are using but lets take PSQL:
its possible to add a RETURNING value when updating
for Example:
UPDATE xxx SET a = <what ever>
WHERE <your condition>
RETURNING b,c;
Related
I am new to C# and need some guidance!
short summary:
I have an application with few forms that is connected to the Access database. Everything is working fine! The user can select the needed item from the combo box that is shown in the label on the next form. Additionally the elements of the table are shown in the datagridview2 on the same form. Every item from the combo box is connected to a different table in the Access database:
private void frmData_Load(object sender, EventArgs e)
{
lblItem.Text = Item;
string connectionString = null;
OleDbConnection con;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\".\\Database_Example.accdb\"";
con = new OleDbConnection(connectionString);
if (lblItem.Text == "X")
{
OleDbCommand cmd2 = new OleDbCommand("SELECT ID, Column1, Column2 FROM X", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd2);
DataTable td = new DataTable();
sda.Fill(td);
dataGridView2.DataSource = td;
}
if (lblItem.Text == "Y")
{
OleDbCommand cmd = new OleDbCommand("SELECT ID, Column1, Column2 FROM Y", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
DataTable td = new DataTable();
sda.Fill(td);
dataGridView2.DataSource = td;
}
}
Now I want to use my application to add new tables to the database. Therefore there are bunch of different approaches on the web.
Problem: I´m looking for an option to automatically create new if-statements once I´ve added new tables in the database. For example for items "Z"; "A"; "B"; ...
Is there a way to do it? Or do I need a different approach?
Greetings :)
We get this question a few times a month and the answer is always the same:
You really need ONE table, with an additional column for your Z, A, B, etc. Make this the first field of the primary key.
Now this:
if (lblItem.Text == "X")
{
OleDbCommand cmd2 = new OleDbCommand("SELECT ID, Column1, Column2 FROM X", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd2);
DataTable td = new DataTable();
sda.Fill(td);
dataGridView2.DataSource = td;
}
// etc
Becomes this:
var td = new DataTable();
using (var con = new OleDbConnection("connection string here"))
using (var cmd = new OleDbCommand("SELECT ID, Column1, Column2 FROM MyTable WHERE Key = ? ", con))
using (var sda = new OleDbDataAdapter(cmd2))
{
cmd.Parameters.Add("?", OleDbType.NChar, 3).Value = lblItem.Text;
sda.Fill(td);
}
No if statement required.
Additionally, do NOT try to re-use your connection object throughout a form instance like that. It really is more efficient to create a new connection for each call to the database.
This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("price");
dt.Columns.Add("image");
dt.Columns.Add("cost");
dt.Columns.Add("totalcost");
if (Request.QueryString["item_name"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
Change
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
to be:
String myquery = "select * from food_items where item_name=#item_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);
Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.
Using parameters like above will help avert the majority of problems you will encounter.
Salam Alekom .
I have comboBox filling it from database as
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand scm = new SqlCommand();
scm.Connection = con;
scm.CommandText = "select * from com";
SqlDataAdapter adpt = new SqlDataAdapter(scm);
DataTable dt = new DataTable();
adpt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = dt.Columns["com_name"].ToString();
comboBox1.ValueMember = dt.Columns["com_id"].ToString();
Where filling with all data that store in the table from database.
This comboBox use also to insert to another table in database
This also poses no problem
The problem when making search in table to get some data. I need to get the text value that store in table and equal to text value of comboBox and sort it in position 0 of this comboBox
I made the search no problem but what property or method that allow me to put the value in position 0 with out affecting the other values that be in combobox
SqlConnection con = new SqlConnection(strcon);
con.Open();
using(SqlCommand scm2 = new SqlCommand())
{
scm2 .Connection = con;
scm2.CommandType = CommandType.StoredProcedure;
scm2 .CommandText = "SP_retrieve_data";
scm2.Parameters.AddWithValue ("#id", textBox1.Text);
SqlDataReader dr = scm2.ExecuteReader();
while (dr.Read())
{
comboBox1. = dr["com_name"].ToString();//what code accept the value
}
}
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 want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..