In the below code ,
Session["FirstName"] = SCode.ToString(); is having error (the name session does not exist in current context).thanks
public DataTable Searchup(string SiteCode = "", string EmployeeRole = "")
{
DbConnection conn = _dataFactory.CreateConnection();
DbDataAdapter da = _dataFactory.CreateDataAdapter();
DataTable dt = null;
try
{
conn.ConnectionString = _connectionString;
conn.Open();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandType = CommandType.Text;
DbParameter param = null;
string sql = "SELECT ID,SITECODE,EMPLOYEEROLE,EMPLOYEEID, FROM " + _tblnpf + "User WHERE Empl <> 'Admin' ";
if (!String.IsNullOrEmpty(SiteCode.Trim()))
{
sql += "AND SiteCode = #SiteCode ";
OracleHelper.CreateParameter(ref da, ref param, "#SiteCode", DbType.String, ParameterDirection.Input, SiteCode);
Session["FirstName"] = SCode.ToString();
}
da.SelectCommand.CommandText = OracleHelper.FixCommandText(sql);
DataTable dt1 = new DataTable("User");
da.Fill(dt1);
Related
I've got the following code:
private void btnAddMatter_Click(object sender, EventArgs e)
{
MatterCode = "";
EntityID = 0;
FeeEarnerID = 0;
OpenedByUserID = 0;
CompanyContactDetailsID = 0;
Description = "";
OurReference = "";
TheirReference = "";
DateOpened = DateTime.Now;
MatterTypeID = 0;
DepartmentID = 0;
ResponsibleUserID = 0;
TrustBankAccountID = 0;
BusinessBankAccountID = 0;
string connectionString = "Data Source=***\\SQLEXPRESS;Initial Catalog=STUPELG;Persist Security Info=True;User ID=***;Password=***";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Matter ( MatterCode, EntityID, FeeEarnerID, OpenedByUserID, CompanyContactDetailsID, Description," +
" OurReference, TheirReference, DateOpened, MatterTypeID, DepartmentID, ResponsibleUserID, TrustBankAccountID, BusinessBankAccountID)" +
" VALUES ( #MatterCode, #EntityID, #FeeEarnerID, #OpenedByUserID, #CompanyContactDetailsID, #Description," +
" #OurReference, #TheirReference, #DateOpened, #MatterTypeID, #DepartmentID, #ResponsibleUserID, #TrustBankAccountID, #BusinessBankAccountID);" +
" SELECT SCOPE_IDENTITY();");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterID", MatterID);
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
cmd.Parameters.AddWithValue("#EntityID", EntityID);
cmd.Parameters.AddWithValue("#FeeEarnerID", FeeEarnerID);
cmd.Parameters.AddWithValue("#OpenedByUserID", OpenedByUserID);
cmd.Parameters.AddWithValue("#CompanyContactDetailsID", CompanyContactDetailsID);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#OurReference", OurReference);
cmd.Parameters.AddWithValue("#TheirReference", TheirReference);
cmd.Parameters.AddWithValue("#MatterTypeID", MatterTypeID);
cmd.Parameters.AddWithValue("#DepartmentID", DepartmentID);
cmd.Parameters.AddWithValue("#ResponsibleUserID", ResponsibleUserID);
cmd.Parameters.AddWithValue("#TrustBankAccountID", TrustBankAccountID);
cmd.Parameters.AddWithValue("#BusinessBankAccountID", BusinessBankAccountID);
cmd.Parameters.AddWithValue("#DateOpened", DateOpened);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UPDATE Matter SET MatterCode = #MatterCode WHERE MatterID = " + MatterCode);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
connection.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Matter " + MatterCode + " successfully created");
}
After the row is inserted, the new MatterID (primary key that is generated automatically) should be copied to the MatterCode field. Currently it works EXCEPT that there is an extra row that is generated at when the button is clicked:
How do I fix this???
Well - this is because your code is executing the INSERT query twice......
connection.Open();
cmd.ExecuteNonQuery(); // first execution
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID); // second execution
I'm not entirely sure what you wanted to do with that SqlDataAdapter - but it's using the same SqlCommand from before, with the INSERT statement, which gets executed a second time......
You can replace this:
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
with
MatterCode = cmd.ExecuteScalar().ToString();
as ExecuteScalar runs the command and returns the value of the first column of the first row of the first resultset.
I am trying to fix some error and mistake which was made and I didn't pay attention in time.
I have two dropdowns (Status is bit) and (OrgUnitId int 0-9).
So the problem is when user selects only one record from these two dropdowns and another dropdown is not selected by default return 0.
But in my example, I want to modify this and create if User select only Status = 1 it should return record where status is 1 and OrgUnit it should return all data without filtering.
So far I wrote these code for catch Status and OrgUnitId from DB and display in DropDownMenu
public void FillOrgUnit()
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlOrgUnit.DataSource = dt;
ddlOrgUnit.DataTextField = "OrgUnitID";
ddlOrgUnit.DataValueField = "OrgUnitID";
ddlOrgUnit.DataBind();
ddlOrgUnit.Items.Insert(0, new ListItem("-- Izaberi Org Jedinicu --", "NULL"));
}
}
public void FillStatus()
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT Status FROM tblZaposleni_AD";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlStatus.DataSource = dt;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "Status";
ddlStatus.DataBind();
ddlStatus.Items.Insert(0, new ListItem("-- Izaberi Status --", "NULL"));
}
}
And here is my main function for filtering data
private void GetReports(XtraReport report)
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
}
report.DataSource = ds;
report.DataMember = ds.Tables[0].TableName.ToString();
}
}
catch (Exception)
{
throw;
}
}
For better understanding what I want and where the problem is I wrote this stored procedure:
DECLARE #Status bit = 1,
#OrgJed int
BEGIN
SELECT PrezimeIme, NetworkLogin, Status, OrgUnitId, DT_Creat, DT_Modif
FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
WHERE (#Status IS NULL OR Status = #Status)
AND (#OrgJed IS NULL OR OrgUnitID = #OrgJed)
END
And here is the result of this stored procedure:
And here is what I get as result in View
It looks to me like when the ALL option is selected, that you are setting the parameter values to the string "NULL", rather than DBNull.Value.
Try replacing this:
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
With this:
if (ddlStatus.SelectedValue == "NULL")
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = DBNull.Value;
else
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
if (ddlOrgUnit.SelectedValue == "NULL")
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = DBNull.Value;
else
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
i dont have an edit template. is it possible for me to add validations on my text box in grid view during edit mode?
It updates the edited fields and works fine, but when I type in special characters, it is still being accepted. How can I validate those editableTextBoxes and prevent the user from entering invalid input?
UPDATE
int prodid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string strprodname = ((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
//string strdesc = ((TextBox)gdview.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string strprice = ((TextBox)gdview.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string strimg = ((TextBox)gdview.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//string strquant = ((TextBox)gdview.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
var regex = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
if (regex.IsMatch(strprice))
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Products set Name='" + strprodname + "', Price ='" + strprice + "' where ProductID =" + prodid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
GetProducts(0);
}
fields not updating
UPDATE getproducts(0)
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = k.GetAllProducts();
gdview.DataBind();
}
datatable:
public DataTable GetAllProducts()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataLayer.DataAccess.AddParameter("#CategoryID", CategoryID, System.Data.SqlDbType.Int, 20);
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("SP_GetAllProducts", parameters);
return dt;
}
UPDATE:
Current Code:
protected void gdview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int prodid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string strprodname = ((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
//string strdesc = ((TextBox)gdview.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string strprice = ((TextBox)gdview.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string strimg = ((TextBox)gdview.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//string strquant = ((TextBox)gdview.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
var regex = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
if (regex.IsMatch(strprodname) && regex.IsMatch(strprice))
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Products set Name='" + strprodname + "', Price ='" + strprice + "' where ProductID =" + prodid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
}
GetProducts(0);
}
var regex_valid_price = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
var regex_no_special_chars = new Regex(#"^[a-zA-Z0-9 ]*$");
if(regex_no_special_chars.IsMatch(strprodname) && regex_valid_price.IsMatch(strprice)){
// do your db inserts
}
Visit http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/validation/defaultcs.aspx
you may get the solution.
int i = int.Parse(rid);
SqlConnection thisconnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\lagenius\JIvandhara ngo\JIvandhara ngo\ngo.mdf;Integrated Security=True;User Instance=True");
thisconnection.Open();
string st = ("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = 4");
DataSet thisdataset = new DataSet();
//string cmdtext = "select * from receipt_info where receipt_no =='" + i + "'";
SqlCommand cmd = new SqlCommand(st, thisconnection);
SqlDataAdapter data_ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
data_ad.Fill(dt);
string st = ("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no =" + i);
First, you should rewrite your statement using parameter
string st = "select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = #Receipt_Number";
And when you've created your SqlCommand - you should add parameter #Receipt_Number to it
cmd.Parameters.Add("#Receipt_Number", SqlDbType.Int);
cmd.Parameters["#Receipt_Number"].Value = i;
When sending parameterized queries, you should use SqlParameter. An example of how to use them are available at http://www.dotnetperls.com/sqlparameter
Basically you structure your query with placeholders, and fill them using the SqlCommands Parameters property.
int searchId = 4;
string connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\lagenius\JIvandhara ngo\JIvandhara ngo\ngo.mdf;Integrated Security=True;User Instance=True"
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (SqlCommand command = new SqlCommand(
"select receipt_no, name, rupees, pay_by, date " +
"from receipt_info where receipt_no = #Id", connection))
{
command.Parameters.Add(new SqlParameter("Id", searchId));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
string st = string.Format("select receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no = {0}",i);
i need update some column in datagridview to database. but don't update to database.
step one: i select datetime from datetimepicker.
step two: show datetime on datagridview.
step tree: i need update/edit on datagridview to database.
Display on Datagridview.
EmpNo fName ChkDate ChkIn ChkOut
00001 Al 01/10/2012 08:02 17:04
00002 Bik 01/10/2012 07:43 18:35
i need update fields "ChkIn" to database.
Code
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),'" + dgvShow.Rows[i].Cells[3].Value + "',102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = '" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "' and [filesTA].EmpNo = '" + dgvShow.Rows[i].Cells[0].Value + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds;
da.Update(ds);
}
}
Error: Update unable to find TableMapping['Table'] or DataTable 'Table'.
I try other code:
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [filesTA]", appConn);
adapter.UpdateCommand = new SqlCommand("UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo", Conn);
adapter.UpdateCommand.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn");
adapter.UpdateCommand.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate");
adapter.UpdateCommand.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo");
DataSet ds = new DataSet();
adapter.Fill(ds);
dgvShow.DataSource = ds;
adapter.Update(ds);
this code not save to database.
Thanks for your time. :D
Type Database:
ChkIn and ChkDate Type DateTime,EmpNo Type NUMERIC
I try
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
using (Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA]" +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')" +
"FROM [WebSP].[dbo].[filesTA]" +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.DateTime, 10, "ChkIn").Value = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value).ToString();
cmd.Parameters.Add("#cDate", SqlDbType.DateTime, 10, "ChkDate").Value = Convert.ToDateTime(dateTimePicker.Value.ToString()).ToString();
cmd.Parameters.Add("#eNo", SqlDbType.Decimal, 10, "EmpNo").Value = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value).ToString();
cmd.ExecuteNonQuery();
}
}
}
Error: Conversion failed when converting date and/or time from character string. T__T
You could try to get rid of the SqlDataAdapter using directly a SqlCommand
Using(Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA] " +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':') " +
"FROM [WebSP].[dbo].[filesTA] " +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn").Value =
dgvShow.Rows[i].Cells[3].Value;
cmd.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate").Value =
dateTimePicker.Value.ToString("yyyy-MM-dd") ;
cmd.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo").Value =
dgvShow.Rows[i].Cells[0].Value ;
cmd.ExecuteNonQuery();
}
Of course, when using parameters, we need to set their values before running the command.
However I really don't understand well the code to update the ChkIn field. That field (according to the Parameter type) is a nvarchar, then why don't you try to format your #cIn value directly in code and avoid the use of Sql Server Replace and Convert functions? Also the 102 is a Date Style. It is used to format Date expressions as strings with the yy.mm.dddd pattern, but you have a string that contains only time info.
For example
After your last edit - changed to this
DateTime chkIN = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value);
DateTime chkDate = Convert.ToDateTime(dateTimePicker.Value.ToString("yyyy-MM-dd"));
decimal empNo = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value) ;
cmd.Parameters.Add("#cIn", SqlDbType.DateTime).Value = chkIN;
cmd.Parameters.Add("#cDate", SqlDbType.DateTime).Value = chkDate;
cmd.Parameters.Add("#eNo", SqlDbType.Decimal).Value = empNo;
Also the syntax used in query could be the source of other problems, but I need to see your connection string.