I want to create a Crystal Report at runtime by selecting the fields for the report from the treeview. The treeview consists of table names and the column names as the child node. After selecting the column names from the treeview, a "Generate Report" button has to be clicked, which will display the Crystal Report of the selected fields. How can I do this?
Public Class Form1
Dim objRpt As CrystalReport1
Dim con As New SqlConnection
Private Function CreateSelectQueryAndParameters() As String
Dim reportDocument As New ReportDocument
Dim paramFields As New ParameterFields
Dim paramField As ParameterField
Dim paramDiscreteValue As ParameterDiscreteValue
Dim query As String = "SELECT "
Dim columnNo As Integer = 0
If CheckBox1.Checked Then
columnNo = columnNo + 1
query = query.Insert(query.Length, "pcode as Column" + columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Code"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
If CheckBox2.Checked Then
columnNo = columnNo + 1
If (query.Contains("Column")) Then
query = query.Insert(query.Length, ", ")
End If
query = query.Insert(query.Length, "pname as Column" +
columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Name"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
For i As Integer = columnNo To 2
columnNo = columnNo + 1
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = ""
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
Next
CrystalReportViewer1.ParameterFieldInfo = paramFields
query += " FROM propdb"
Return query
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
objRpt = New CrystalReport1()
con.ConnectionString = "Data Source=MY-PC; Initial Catalog=hrmdb; Integrated Security=True"
con.Open()
Dim query As String = CreateSelectQueryAndParameters()
If Not query.Contains("Column") Then
MessageBox.Show("No selection to display!")
Return
End If
Try
**' I DON'T KNOW WHAT CODE TO ADD HERE'**
CrystalReportViewer1.ReportSource = objRpt
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End Sub
End Class
I had a similar program in C#, but they used Access in it and I am using SQL Server now:
public partial class Form1 : Form
{
CrystalReport1 objRpt;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
objRpt = new CrystalReport1();
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\db1.mdb";
//Get Select query Strring and add parameters to the
//Crystal report.
string query = CreateSelectQueryAndParameters();
//if there is no item select,then exit from the method.
if (!query.Contains("Column"))
{
MessageBox.Show("No selection to display!");
return;
}
try
{
OleDbConnection Conn = new OleDbConnection(connString);
OleDbDataAdapter adepter = new OleDbDataAdapter(query, connString);
DataSet1 Ds = new DataSet1();
adepter.Fill(Ds, "Customer");
objRpt.SetDataSource(Ds);
crystalReportViewer1.ReportSource = objRpt;
}
catch (OleDbException oleEx)
{
MessageBox.Show(oleEx.Message);
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
/// <summary>
/// This method is used to
/// 1. create SELECT query according to the selected column names and
/// 2. create parameters and assign values for that parameter that correspond to
/// the crystal report.
/// NOTE: This parameter is used to display column names of the Crystal Report
/// according to the user selection.
/// </summary>
/// <returns></returns>
private string CreateSelectQueryAndParameters()
{
ReportDocument reportDocument;
ParameterFields paramFields;
ParameterField paramField;
ParameterDiscreteValue paramDiscreteValue;
reportDocument = new ReportDocument();
paramFields = new ParameterFields();
string query = "SELECT ";
int columnNo = 0;
if (chbCode.Checked)
{
columnNo++;
query = query.Insert(query.Length, "Code as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Customer Code";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbFirstName.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "FirstName as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "First Name";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbLastName.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "LastName as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Last Name";
paramField.CurrentValues.Add(paramDiscreteValue);
// Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbAddress.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "Address as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Address";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbPhone.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "Phone as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Phone";
paramField.CurrentValues.Add(paramDiscreteValue);
// Add the paramField to paramFields
paramFields.Add(paramField);
}
//if there is any remaining parameter, assign empty value for that
//parameter.
for (int i = columnNo; i < 5; i++)
{
columnNo++;
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
crystalReportViewer1.ParameterFieldInfo = paramFields;
query += " FROM Customer" ;
return query;
}
}
Related
I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.
using System.Data.SqlClient;
namespace EHR
{
public partial class imagery : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\wittyse\Desktop\database_EHR\EHR.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
DataTable dt2 = new DataTable();
public imagery()
{
InitializeComponent();
}
public void readdatagrid1()
{
//con.Open();
SqlDataAdapter dpeo = new SqlDataAdapter("Select Img_ID,PEOPLE_INFO.people_ID,PEOPLE_INFO.Name,Imgs,Result from PEOPLE_INFO,IMAGERY_DIAGNOSTIC,MG_NAM where IMAGERY_DIAGNOSTIC.Img_ID=MG_NAM.Mg_nm_ID and PEOPLE_INFO.people_ID=IMAGERY_DIAGNOSTIC.People_ID", con);
DataSet dpep = new DataSet();
dpeo.Fill(dpep, "IMAGERY_DIAGNOSTIC");
dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
con.Close();
}
private void imagery_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource = null;
readdatagrid1();
SqlDataAdapter dz = new SqlDataAdapter("Select * from MG_NAM order by Mg_nm_ID", con);
DataSet dzo = new DataSet();
dz.Fill(dzo, "MG_NAM");
comboBox1.DataSource = dzo.Tables["MG_NAM"];
comboBox1.DisplayMember = "Imgs";
SqlDataAdapter da = new SqlDataAdapter("Select Name from PEOPLE_INFO order by people_ID", con);
DataSet ds = new DataSet();
da.Fill(ds, "PEOPLE_INFO");
comboBox2.DataSource = ds.Tables["PEOPLE_INFO"];
comboBox2.DisplayMember = "Name";
con.Close();
}
public int comck=0;
public int idx;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select Mg_nm_ID,Imgs from MG_NAM where Imgs='" + comboBox1.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox4.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
idx = Convert.ToInt32(textBox4.Text);
}
dr.Close();
comck = 1;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(id+" index is "+comboBox1.SelectedIndex,"info");
}
public int comck2 = 0;
public int id;
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select people_ID,Name from PEOPLE_INFO where Name='" + comboBox2.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
id = Convert.ToInt32(textBox2.Text);
}
dr.Close();
comck2 = 1;
}
private void button2_Click(object sender, EventArgs e)
{
if (comck == 0 & comck2 == 0 || textBox3.Text == "")
{
MessageBox.Show("you must select or inter data","info");
}
else
{
con.Close();
cmd = new SqlCommand("Insert into IMAGERY_DIAGNOSTIC(People_ID,Mg_Nam,Result) values ('" + id + "','" + idx + "','" + textBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added new IMAGERY DIAGNOSTIC ", "ADD", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
// MessageBox.Show("info save"+comboBox1.SelectedIndex," info ");
}
private void button3_Click(object sender, EventArgs e)
{
if (selectgrid == 0)
{ MessageBox.Show("you must select record to delet it","Info",MessageBoxButtons.OK,MessageBoxIcon.Information); }
else
{
cmd = new SqlCommand("Delete From IMAGERY_DIAGNOSTIC Where Img_ID='" + bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You delete recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
}
public int bindex;
public int selectgrid = 0;
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
textBox1.Text = row.Cells["People_ID"].Value.ToString(); //roll type to update
comboBox2.Text = row.Cells["Name"].Value.ToString();
textBox3.Text = row.Cells["Result"].Value.ToString();
string dex = row.Cells["Img_ID"].Value.ToString();
bindex = Convert.ToInt32(dex); //Bld_ID in integer format | for Query
selectgrid = 1;
}
}
}
}
replace the following code dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
with
dataGridView1.DataSource = new BindingSource { DataSource =dpep.Tables["IMAGERY_DIAGNOSTIC"] };
I am dynamically creating a crystal report. When I run the program and click on a button, I get "Parameter is incorrect" information box. How can I resolve this?
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.ReportSource
Imports CrystalDecisions.Shared
Imports CrystalDecisions.Windows.Forms
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class Form1
Dim objRpt As CrystalReport1
Dim con As New SqlConnection
Private Function CreateSelectQueryAndParameters() As String
Dim paramFields As ParameterFields
Dim paramField As ParameterField
Dim paramDiscreteValue As ParameterDiscreteValue
paramFields = New ParameterFields
Dim query As String = "SELECT "
Dim columnNo As Integer = 0
If CheckBox1.Checked Then
columnNo = columnNo + 1
query = query.Insert(query.Length, "pcode as Column" + columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Code"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
If CheckBox2.Checked Then
columnNo = columnNo + 1
If query.Contains("Column") Then
query = query.Insert(query.Length, ", ")
End If
query = query.Insert(query.Length, "pname as Column" + columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Name"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
For i As Integer = columnNo To 2
columnNo = columnNo + 1
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = ""
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
Next
CrystalReportViewer1.ParameterFieldInfo = paramFields
query += " FROM propdb"
TextBox1.Text = query
Return query
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As SqlConnection
Dim connString As String
Dim query As String
connString = "Data Source=RANJITHA-PC;Initial Catalog=hrmdb;Integrated Security=True"
cnn = New SqlConnection(connString)
cnn.Open()
query = CreateSelectQueryAndParameters()
If Not query.Contains("Column") Then
MessageBox.Show("No selection to display!")
Return
End If
Dim adepter As New SqlDataAdapter(query, cnn)
Dim Ds As New DataSet2
adepter.Fill(Ds, "propdb")
MsgBox(Ds.Tables(0).Rows.Count)
cnn.Close()
objRpt = New CrystalReport1()
objRpt.SetDataSource(Ds.Tables(0))
Me.CrystalReportViewer1.ReportSource = objRpt
Me.CrystalReportViewer1.Refresh()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub End Class
Seems you have a issue in you for-loop, should changed to
For i As Integer = columnNo+1 To 2
paramField = New ParameterField()
paramField.Name = "col" + i.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = ""
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
Next
And put a break pint in CrystalReportViewer1.ParameterFieldInfo = paramFields and check the parameter names
I want to have a auto suggestion textbox which will show the name of employee after typing a specific letter. The name is present in the employee table in three columns i.e firstname, middlename, lastname.
I have tried a code for this but it can show only one column of the table i.e the firstname.
How to concatenate all the three columns so that they are suggested in the textbox.
My code:
Dim strSql As String = "select P_Firstname, P_MiddleName, P_LastName from Patient_Registration"
Dim dtb As New DataTable
Using cnn As New SqlConnection(conn)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
txtsearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtsearch.AutoCompleteSource = AutoCompleteSource.CustomSource
If dtb.Rows.Count > 0 Then
Dim i As Integer = 0
For i = 0 To (dtb.Rows.Count - 1)
txtsearch.AutoCompleteCustomSource.Add(dtb.Rows(i)("P_FirstName"))
Next
End If
Use:
For i = 0 To (dtb.Rows.Count - 1)
txtsearch.AutoCompleteCustomSource.Add(dtb.Rows(i)("P_FirstName") &
dtb.Rows(i)("P_MiddleName") &
dtb.Rows(i)("P_LastName"))
Next
Instead of:
For i = 0 To (dtb.Rows.Count - 1)
txtsearch.AutoCompleteCustomSource.Add(dtb.Rows(i)("P_FirstName"))
Next
<asp:TextBox ID="ddlcenter" runat="server" Font-Size="10px" TabIndex="1" Width="150px"
Style="text-transform: capitalize;"
placeholder="Type Center Name/Code" autocomplete="off"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetCenter" MinimumPrefixLength="2" CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10" TargetControlID="ddlcenter" UseContextKey="true"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false" CompletionListCssClass="completionList"
CompletionListHighlightedItemCssClass="itemHighlighted" CompletionListItemCssClass="listItem">
</cc1:AutoCompleteExtender>
[enter image description here][1]
[1]: https://i.stack.imgur.com/g6TR9.png
Showing above result.
enter code here
My code is :
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCenter(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
string cmdText = "Select centername from Center_Master WHere Active=1 and centername like '%' +#SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmdText += " order by centername ";
cmd.CommandText = cmdText;
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["centername"].ToString());
}
}
conn.Close();
return customers;
}
}
}
I have a web app, where when a page loads, the address details are extracted from the database and displayed in the corresponding text-fields. However when I try to update and save the data, the data doesn't get updated.
However the same works fine when the extraction of data happens through the click of a button.
here's the code :
public partial class Address : System.Web.UI.Page
{
string global;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
global = Session["ID"].ToString();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT PermanentAdd,PermanentAdd2, HomePlace, HomeState, HomePin FROM EMPLOYEE_FULLADDRESS_TABLE WHERE EmployeeID = '" + global + "'", con);
SqlDataReader x = cmd.ExecuteReader();
while (x.Read())
{
TextBox1.Text = (string)x["PermanentAdd"];
TextBox1.Enabled = false;
TextBox5.Text = (string)x["PermanentAdd2"];
TextBox5.Enabled = false;
TextBox2.Text = (string)x["HomePlace"];
TextBox2.Enabled = false;
TextBox3.Text = (string)x["HomeState"];
TextBox3.Enabled = false;
State.Items.FindByText(State.SelectedItem.Text).Selected = false;
State.Items.FindByText(TextBox3.Text).Selected = true;
State.Enabled = false;
TextBox4.Text = (string)x["HomePin"];
TextBox4.Enabled = false;
}
x.Close();
con.Close();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
// global = Session["ID"].ToString();
//string insert = "UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'";
SqlCommand cmd1 = new SqlCommand("UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'", con);
cmd1.Parameters.AddWithValue("#PermanentAdd", TextBox1.Text);
cmd1.Parameters.AddWithValue("#PermanentAdd2", TextBox5.Text);
cmd1.Parameters.AddWithValue("#HomePlace", TextBox2.Text);
if (State.SelectedItem.Text == "--Select--")
{
State.SelectedItem.Text = TextBox3.Text;
}
cmd1.Parameters.AddWithValue("#HomeState", State.SelectedItem.Text);
cmd1.Parameters.AddWithValue("#HomePin", TextBox4.Text);
cmd1.ExecuteNonQuery();
con.Close();
lblmsg.Text = "DATA Updated Successfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception exp)
{
lblmsg.Text = exp.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
// static int count = 0;
protected void EditButton_Click(object sender, EventArgs e)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
//TextBox3.Enabled = true;
TextBox4.Enabled = true;
TextBox5.Enabled = true;
State.Enabled = true;
}
please help.
I think you have commented out your global / employeeid assignment?
// global = Session["ID"].ToString();
You should also change this to a parameter in your SQL.