C# programming with window forms - forms

private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
int ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtFname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtAddress.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update student set name ='"+txtName.Text+"', fathername= '"+txtFname.Text+"', address= '"+txtAddress.Text+"' where id = ID", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Display();
MessageBox.Show("Record is Updated");
When i run this code then my whole database table is updated with the current values and i can't understand the problem

"where id = ID" condition is always true so all records are affected. You need to actually set a value for "ID". Perhaps you need to write
"where id =" + ID.ToString()

Related

How to dynamically and correctly change a query in Command Table for Crystal Reports file?

I have many rpt files. I want to change the query for each report using C#. There are several ways to do this changes.
First way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(123) * FROM sys.all_objects";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It is not the best way. The method SetSQLCommand does not work when the query has any parameters. Even if you set value for each parameter, SetSQLCommand does not work. The example with a parameter which does not work:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(1) * FROM sys.all_objects WHERE name = {?strName}";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetParameterValue("strName", "Text");
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It returns an error. This method does not work with parameters!
Second way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
ISCDReportClientDocument rcd = null;
rcd = rptDoc.ReportClientDocument as ISCDReportClientDocument;
CommandTable rTblOld;
CommandTable rTblNew;
rTblOld = rcd.Database.Tables[0] as CommandTable;
rTblNew = rcd.Database.Tables[0].Clone(true) as CommandTable;
rTblNew.CommandText = "SELECT TOP(1) * FROM sys.all_objects";
try
{
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
rcd.VerifyDatabase();
}
catch (Exception ex) { rcd.Close(); }
rcd.SaveAs(rcd.DisplayName, "D:\\Temp_02\\", 1);
rcd.Close();
}
This is also not the best way. The method SetLocalTableEx does a struct of the report is bad. After run SetLocalTableEx, attribute ConnectionInf.UserId have value NULL also the Name of connection
After SetTableLocationEx:
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
String UserID;
UserID = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo.UserID;
if (UserID == null) MessageBox.Show("UserID has NULL");
UserId has value NULL
Also, before run SetTableLocationEx, Connection Name is MSODBCSQL11
enter image description here
After run SetTableLocationEx, Connection Name is Command
enter image description here
So,
how do dynamic and correctly to change the query in CommandTable for Crystal Reports file?
Thanks,
Artem
You are using command in Crystal Report which is the best way when doing and displaying a data from database to crystal report but unfortunately you do it in Code Behind.
My Question is:
Why don't you do it in Command of Crystal Report itself?
see this link for more info.

Unable to know how to link data between two tables

I'm learning RESTful webservices from javabrains website. Here there is a section named Comments and this is related to a message, But I'm unable to know How Can I link these both.
Below is my SQL Tables for Messages and comments.
Messages
Comments
Here Basically, both look pretty same(The table design), but the values differ. And I'm using the below method to send the data.
public Comment addComment(long messageId, Comment comment) throws Exception {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("/config.properties"));
String userName = properties.getProperty("user");
String password = properties.getProperty("pass");
String url = properties.getProperty("Sqldburl");
int key = 0;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(url, userName, password);
String query = "select count(*) from Comments";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
rs.next();
key = rs.getInt(1);
} catch (Exception e) {
System.out.println(e);
}
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(url, userName, password);
String query = "insert into Comments(id, message, author) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, key);
ps.setString(2, comment.getMessage());
ps.setString(3, comment.getAuthor());
ps.executeQuery();
} catch (Exception e) {
System.out.println(e);
}
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(url, userName, password);
String query = "select * from Comments where messageId=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setLong(1, messageId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
comment.setAuthor(rs.getString("Author"));
comment.setId(rs.getInt("Id"));
comment.setMessage(rs.getString("message"));
}
} catch (Exception e) {
System.out.println(e + "b3");
}
return comment;
}
After writing this code, I've realized that Here I'm adding a comment for sure into Comments table, But it is no where linked to the Messages.
I know a way, that is I've create a new column in the Comments table and using join operation, I need to update the same messageId in comments table. But I want to know if there is a better way of getting this done, without using the concept of joins.
In MessageBean, there is a map declared as below.
private Map<Long, Comment> comments = new HashMap<>();
#XmlTransient
public Map<Long, Comment> getComments() {
return comments;
}
public void setComments(Map<Long, Comment> comments) {
this.comments = comments;
}
can I take any advantage of this to avoid join?

Crystal Report doesn't show data when generated

When I generate it on runtime, it doesn't show any data. But it does when I check on the 'Main Report Preview' of VS 2010. I have also checked my stored procedure, it does produce data when I execute it. What seems to be the problem?
This is my code in page_load:
protected void Page_Load(object sender, EventArgs e)
{
string municipio = Request.QueryString["municipio"];
string ano = Request.QueryString["ano"];
string cnpj = Server.UrlDecode(Request.QueryString["cnpj"]);
DataTable dt;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection cnn = new SqlConnection(CS))
{
cnn.Open();
//stored procedure
SqlCommand cmd = new SqlCommand("spConsultaRelatorioCompleto", cnn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ano", ano);
cmd.Parameters.AddWithValue("#municipio", municipio);
cmd.Parameters.AddWithValue("#cnpj", cnpj);
//read access to the database
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
//datatable with data
dt = new DataTable("dt");
//datatable with datareader's data
dt.Load(dr);
da.Fill(dt);
}
ReportDocument MeuRelatorio = new ReportDocument();
MeuRelatorio.Load(Server.MapPath("RelatorioConvenio.rpt"));
MeuRelatorio.SetDataSource(dt);
CrystalReportViewer1.ReportSource = MeuRelatorio;
}
}
}
I give some values in another webform when I click the button below:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Redirect("RelatorioGerado.aspx?municipio=" + ddlmunicipioconvenente.Text + "&cnpj=" + Server.UrlEncode(tbcnpjconvenente.Text) + "&ano=" + tbAno.Text);
}

The column name ... was not found in this ResultSet

We are using java jdk 1.7.0_45, postgresql jdbc connector postgresql-9.3-1100.jdbc41.jar.
Here is a synopsis of our problem, as much as possible of code pasted below.
This code:
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("d.deptId"));
Produces the error:
org.postgresql.util.PSQLException: The column name d.deptId was not found in this ResultSet.
This code:
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("deptId"));
Produces no error.
Is there a way, besides removing the "d." from the first query, to make the first code snippet not throw the error message?
Here is the source code:
public class JoinTest {
#Test
public void test(){
boolean pass = false;
try {
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
String label = rs.getMetaData().getColumnLabel(1); // What do you get?
System.out.println("label = " + label);
while (rs.next()){
System.out.println(rs.getInt("d.deptId"));
pass = true;
}
} catch (SQLException e) {
e.printStackTrace();
pass=false;
}
assertTrue(pass);
}
#Test
public void test2(){
boolean pass = false;
try {
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("deptId"));
pass = true;
}
} catch (SQLException e) {
e.printStackTrace();
pass=false;
}
assertTrue(pass);
}
}
public class DbConn {
private static String url = "jdbc:postgresql://server:port/schema";
private static Properties props = new Properties(); {
props.setProperty("user","userid");
props.setProperty("password","passwprd");
}
private Connection conn;
private DbConn(){}
private static DbConn instance;
public static DbConn getInstance() throws SQLException{
if (instance == null){
instance = new DbConn();
instance.conn = DriverManager.getConnection(url, props);
}
return instance;
}
public ResultSet doQuery(String query) throws SQLException{
Logger.log("DbConn.doQuery: " + query);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
}
}
}
The query:
select d.deptId from Depts d
produces a single-column resultset with the result-alias "deptId". There is no "d.deptId" column. If you want one, you can request that as the column alias instead:
select d.deptId AS "d.deptId" from Depts d
PgJDBC can't do anything about this because it has no idea that the resultset column "deptId" is related to the "d.deptId" in the select-list. Teaching it about that would force it to understand way more about the SQL it processes than would be desirable, and lead to maintenance and performance challenges.
The second one works - why isn't that acceptable?
You can also do this:
System.out.println(rs.getInt(1));
If you change the query you have to change the code, too.

In what order C# execute sqlstatement?

I have two table related by foreign and primary key constraint.The Visit_Number in Patient table must exist in the Visit table.In my code in define create two instance of my connection string such that i can use one instance to insert record:VisitNumber in Visit table first and then the other instance to insert record in the patient table,with the believe that the cord runs from top to bottom.But this was n't the case. i still get foreign key constraint errror:
Error Number:547
Error MessageThe INSERT statement conflicted with the FOREIGN KEY constraint "Patient_Vist_FK".
The conflict occurred in database "TestDB", table "dbo.Visit", column 'Visit_Number'.
The statement has been terminated.On line Number: 1
meaning the code is running as i expected. Please do you have a better approach and why isn't mine working
code:
protected void btn_save_Click(object sender, EventArgs e)
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
SqlConnection con2 = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
SqlCommand cmd = new SqlCommand(insert_statement, con);
SqlCommand cmd2 = new SqlCommand(insert_stament2, con2);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
try
{
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script language=javascript>alert('Record Sucessfully Inserted!');</script>");
//Success_Message.Text = "Record inserted";
txtpatientNum.Text = String.Empty;
txtfirstName.Text = String.Empty;
txtlastname.Text = String.Empty;
txtVistNumber.Text = String.Empty;
DropDownList1.Text = String.Empty;
val_age.Text = String.Empty;
}
}
}
catch (SqlException ex)
{
{
VisitError_Message.Text = "Error Number:" + ex.Number.ToString() + " Error Message" + ex.Message + "On line Number" + ": " + ex.LineNumber;
}
}
catch (NullReferenceException nullexception)
{
VisitError_Message.Text = "Error Occurred, Error Type:" + nullexception.GetType().ToString() + "Error Message:" + nullexception.Message;
}
catch (DllNotFoundException dllexception)
{
VisitError_Message.Text = dllexception.GetType().ToString() + dllexception.Message;
}
finally
{
con.Close();
}
}
you not excuting you cmd2, you must execute the insert Visit_Number in cmd2 then excute your cmd, you can test this code
using (con2)
{
con2.Open();
cmd2.ExecuteNonQuery();
}
then you can excute your cmd
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
}
and you can do the work with the same connexion if you want
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
using(con)
{
con.open;
SqlCommand cmd2 = new SqlCommand(insert_stament2, con);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd2.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(insert_statement, con);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.ExecuteNonQuery();
}