I have 3 Tables
LaminationTitle**
LaminationTitleRelation
Papertypemaster
I Want to update Values of"LaminationTitleRelation" table which comes from CheckboxList... Below is my Update Form....
Lamination Title in Below form Updated in LaminationTitle Table, where as
Checkbox List Items should Update in LaminationTitleRelation Table
Note: if "Papertypeid" in LaminationTitleRelation and Items Checked are different then it should be add.
Plz help me
Use the following query:
query = "Create Table #PaperTypeMapping(LaminationTitleId int, PaperTypeId int)";
//For each value of Paper Type Id you will need to insert a row
query = "Insert Into #PaperTypeMapping(LaminationTitleId, PaperTypeId) Values(#laminationId, #paperTypeId)";
//Update existing values
query = "Update OldMapping Set OldMapping.ActiveStatus = 1 FROM LaminationTitleRelation OldMapping Inner join #PapertTypeMapping NewMapping ON OldMapping.LamTitleId = NewMapping.LaminationTitleId and OldMapping.PaperTypeId = NewMapping.PaperTypeId"
//Insert new values
query = "Insert into LaminationTitleRelation(lamTitleId, PapertTypeId, ActiveStatus) Select LaminationTitleId, PapertTYpeId, 1 From #PaperTypeMapping NewMapping where NOT EXISTS(SELECT 1 FROM LaminationTitleRelation OldMapping WHERE OldMapping.LamTitleId = NewMapping.LaminationTitleId and OldMapping.PaperTypeId = NewMapping.PaperTypeId)";
or alternatively you can use the following link a built in utility by MS SQL Merge
protected void btnUpdate_Click(object sender, EventArgs e) {
DB = new DBFunctions();
string vItems = mGetSelectedItems();
string vQuery = "Update laminationtitle Set title='" + txtLaminationTitle.Text + "',laminationtypeid='" + ddlProductType.SelectedValue + "' where laminationid='" + Request.QueryString["laminationid"] + "'";
int x = DB.SetData(vQuery);
DataTable dSelect = new DataTable();
DataTable dAll = new DataTable();
DB = new DBFunctions();
DB1 = new DBFunctions();
if (x > 0) {
int y = DB.SetData("delete from laminationtitlepapertyperelation where lamtitleid=" + Request.QueryString["laminationid"]);
if (y > 0) {
string[] values = vItems.Split(',');
for (int i = 0; i < values.Length; i++) {
vQuery = "insert into laminationtitlepapertyperelation(lamtitleid, papertypeid, activestatus)VALUES('" + Request.QueryString["laminationid"].ToString() + "','" + values[i] + "',1)";
DB.SetData(vQuery);
ScriptManager.RegisterStartupScript(this, GetType(), " Update Lamination Title", "alert('Lamination " + '"' + txtLaminationTitle.Text + '"' + " Title Updated Sucessfully');window.location='ManageLaminationTitle.aspx';", true);
}
}
}
}
Related
I am working on a school project and for some reason my mysql database doesn't update despite no of row changed is more than 0 and triggering the Update sucessful alert. It also manage to only update my image data from my fileupload.
**admin_products_details_edit.aspx.cs**
protected void btn_ProdEdit_Click(object sender, EventArgs e)
{
int result = 0;
string image = "";
if (FileUpload_ProdImg.HasFile == true)
{
image = "images\\" + FileUpload_ProdImg.FileName;
img_result.ImageUrl = FileUpload_ProdImg.FileName;
}
else
{
image = img_result.ImageUrl;
}
Product Prod = new Product();
string datProdID = lbl_ProdID.Text;
string datProdName = tb_ProdName.Text;
string datProdDesc = tb_ProdDesc.Text;
string datProdImg = img_result.ImageUrl;
decimal datProdPrice = decimal.Parse(tb_ProdPrice.Text);
int datProdCal = int.Parse(tb_ProdCal.Text);
int datStockLvl = int.Parse(tb_StockLvl.Text);
result = Prod.ProductUpdate(datProdID, datProdName, datProdDesc, datProdImg, datProdPrice, datProdCal, datStockLvl);
if (result > 0)
{
string saveimg = Server.MapPath(" ") + "\\" + image;
FileUpload_ProdImg.SaveAs(saveimg);
Response.Write("<script>alert('Update successful');</script>");
Response.Redirect("admin_products_details.aspx?ProdID=" + datProdID);
}
else
{
Response.Write("<script>alert('Update fail');</script>");
}
}<-The code for the button edit event trigger
**Product.cs**
...public int ProductUpdate(string upID, string upName, string upDesc, string upImg, decimal upPrice, int upCal, int upstkLvl)
{
string queryStr = "UPDATE Products SET" + " ProdName = #productName, " + " ProdDesc = #productDesc, " + " ProdImg = #productImage, " + " ProdPrice = #productPrice, " + " ProdCalorie = #productCal, " + " StockLevel = #productStkLvl " + " WHERE ProdID = #productID";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#productID", upID);
cmd.Parameters.AddWithValue("#productName", upName);
cmd.Parameters.AddWithValue("#productDesc", upDesc);
cmd.Parameters.AddWithValue("#productImage", upImg);
cmd.Parameters.AddWithValue("#productPrice", upPrice);
cmd.Parameters.AddWithValue("#productCal", upCal);
cmd.Parameters.AddWithValue("#productStkLvl", upstkLvl);
conn.Open();
int nofRow = 0;
nofRow = cmd.ExecuteNonQuery();
conn.Close();
return nofRow;
}<-The code for updating the mysql database,located in a different cs file,titled Product.cs
My mysql database table is called Products
Thank you very much for your help in advance.
I have a SQL Server database with a table QC and columns A, B, C, D, E,
Comment.
What I am trying to do is to read the data from the columns and display it in a label. But there is not always data in all columns.
Expected output is:
2.5|2.1
if there is data only in A and B column. But I get:
2.5|2.1| |||||
This is my code:
SqlCommand cmd = new SqlCommand("SELECT TOP 1 * FROM [TableQC] ORDER BY id DESC", conn);
SqlDataReader reader = cmd.ExecuteReader();
string temp = "";
string temp1 = "";
while (reader.Read())
{
temp += reader["A"].ToString() + "|";
temp += reader["B"].ToString() + "|";
temp += reader["C"].ToString() + "|";
temp += reader["D"].ToString() + "|";
temp += reader["E"].ToString() + "|";
temp1 += reader["Comment"].ToString();
//temp += "<br/>";
}
conn.Close();
label1.Text = temp;
label2.Text = temp1;
As Mong Zhu pointed out, check while reading the column values:
if (!string.IsNullOrEmpty(reader.GetString("A")))
This will test each column for null value and replace it with an empty string.
To avoid a dangling | delimiter at the end, work with an array of strings you the Join()
while (reader.Read())
{
// create an array big enough to hold all columns
object[] qc = new object[reader.FieldCount];
// iterate over all columns of your reader
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader[i] == reader["Comment"])
{
label2.Text = reader.GetSqlString(i).IsNull ? null : reader.GetSqlString(i).Value;
}
else
{
// add to array
qc[i] = reader.GetValue(i);
}
}
label1.Text = string.Join("|", qc.OfType<string>());
}
However it seems to didn't tell the actual data type of columns A, B, etc. and assuming them to be of string/character data type turned out to be false.
Depending on your actual data types, you will have to edit the filtering Linq query to the actual type like qc.OfType<decimal>() or only filter for null values like qc.Where(v => !(v is DBNull)).
You can do this in the query. Basically you want concat_ws(), but that is not available in SQL Server. Instead:
SELECT TOP 1 STUFF( (COALESCE('|' + A, '') +
COALESCE('|' + B, '') +
COALESCE('|' + C, '') +
COALESCE('|' + D, '') +
COALESCE('|' + E, '') +
COALESCE('|' + Comment, '')
), 1, 1, ''
) as abcde
FROM [TableQC]
ORDER BY id DESC
Thanks you all for helping me and resolving my problem. This is the code that works for me:
SqlCommand cmd = new SqlCommand("SELECT TOP 1 * FROM [TableQC] ORDER BY id DESC", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// create an array big enough to hold all columns
object[] qc = new object[reader.FieldCount];
// iterate over all columns of your reader
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader[i] == reader["Comment"])
{
lblMessage1.Text = reader.GetSqlString(i).IsNull ? null : reader.GetSqlString(i).Value;
}
else
{
// add to array
qc[i] = reader.GetValue(i);
}
}
lblMessage.Text = string.Join("|", qc.OfType<double>());
}
conn.Close();
Thanks you a lot once more time.
Why the ExecuteNonQuery catch exception {"validation error for column \"ORGTABLE\".\"FIKEYID\", value \"* null *\""}
string stValuesPlaceHolder = "#p0";
for (int iii = 1; iii < liststFieldValuesNoKeyId.Count; iii++)
stValuesPlaceHolder += ", #p" + (iii).ToString();
FbTransaction fbTransaction = fbConn.BeginTransaction();
FbCommand fbCmd = new FbCommand("INSERT INTO " + stTableName + "(" + stFieldNamesNoKeyId + ") VALUES ( " + stValuesPlaceHolder + " )", fbConn, fbTransaction);
for (int iii = 0; iii < liststFieldValuesNoKeyId.Count; iii++) {
string stPlaceHolder = "#p" + (iii).ToString();
string stValue = liststFieldValuesNoKeyId[iii];
fbCmd.Parameters.AddWithValue(stPlaceHolder, stValue);
}
fbCmd.ExecuteNonQuery();
fbTransaction.Commit();
The stTableName is OrgTable.
The fields names are:
fstPriority, fstInfo, fstDateCreated, fstDateModified, fiKeyID.
The field definitions are:
fstPriority VARCHAR(30), fstInfo VARCHAR(100), fstDateCreated VARCHAR(30), fstDateModified VARCHAR(30), fiKeyID INTEGER PRIMARY KEY
In this section of the code:
stFieldNamesNoKeyId = "fstPriority, fstInfo, fstDateCreated, fstDateModified".
stValuesPlaceHolder = "#p0, #p1, #p2, #p3"
Four
fbCmd.Parameters.AddWithValue:
stPlaceHolder = "#p0" ... stValue = "1st value";
stPlaceHolder = "#p1" ... stValue = "2nd value";
stPlaceHolder = "#p2" ... stValue = "3rd value";
stPlaceHolder = "#p3" ... stValue = "4th value";
I did not add a value for fiKeyID as it as the PRIMARY KEY.
I did not add a value for fiKeyID as it as the PRIMARY KEY.
So you try to insert a NULL primary key. This is not allowed.
http://www.firebirdsql.org/manual/nullguide-keys.html
NULLs are never allowed in primary keys. A column can only be (part of) a PK if it has been defined as NOT NULL, either in the column definition or in a domain definition.
Then, you might want to ask server for auto-generating IDs. There are few ways of doing it.
Firebird 3 comes with auto-inc column type, for example. Which is a syntactic sugar over tools that were explicitly used by database developer before.
Firebird 2 and prior versions used GENERATORS (aka SQL SEQUENCE) to achieve it.
You have to make a BEFORE-INSERT (or BEFORE-INSERT-OR-UPDATE) trigger on the table, that would fill the ID field from the generator, if the ID field was NULL. http://www.firebirdfaq.org/faq29/
CREATE GENERATOR gen_t1_id;
SET GENERATOR gen_t1_id TO 0;
set term !! ;
CREATE TRIGGER T1_BI FOR T1
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
if (NEW.ID is NULL) then NEW.ID = GEN_ID(GEN_T1_ID, 1);
END!!
set term ; !!
There it boils down to your SQL access library.
Because typically after you inserted the row - you have to know its ID.
If you do not care about that ID of newborn row, you may skip the rest.
But if you want to both insert the row and know its ID then it boils down to another choice.
Low-tech SQL-only libraries would force you to take a doubletrip:
SELECT GEN_ID(GEN_T1_ID, 1) FROM RDB$DATABASE or SELECT NEXT VALUE FOR GEN_T1_ID FROM RDB$DATABASE would reserve you a free token, then you would explicitly assign your ID PK-column to that value and insert it together with data columns, bypassing the trigger.
Or with advanced SQL libraries you may ask Firebird to auto-calculate value and report it to you: INSERT INTO tablename(data1,data2,dataq3) VALUES (1,2,3) RETURNING id. See https://en.wikipedia.org/wiki/Insert_(SQL)#Retrieving_the_key
Whether you need to learn the inserted ID or not, and whether your SQL library supports INSERT-RETURNING command or not - it is up to you to decide.
However when I do Google search ( it is www.google.com ) it comes with many links about C# Firebird Insert Returniung for many different C# SQL libraries, and again only you can tell which one you use. For few examples from different libs:
http://www.ibprovider.com/eng/documentation/firebird_21_adonet.html
http://www.sql.ru/forum/actualutils.aspx?action=gotomsg&tid=720869&msg=8075816
Retrieve last id from Firebird db table
Firebird insert...returning asp.net
https://social.msdn.microsoft.com/Forums/en-US/e7099cfb-7809-460a-aae9-79a2bd703454/how-i-can-return-the-id-after-insert-a-record-into-a-database-firebird-25-with-linq?forum=adodotnetentityframework
et cetera
Definitions:
public const string stMAIN_TABLE_NAME = " OrgTable ";
public const string stDELETED_TABLE_NAME = " BackupTable ";
public const string stFIELD_DEFINITIONS = " fstPriority VARCHAR(30)" +
", fstInfo VARCHAR(100)" +
", fstDateCreated VARCHAR(30)" +
", fstDateModified VARCHAR(30)" +
", fiKeyID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY ";
public const string stFIELD_NAMES_NO_KEY_ID = " fstPriority" +
", fstInfo" +
", fstDateCreated" +
", fstDateModified ";
public const string stFIELD_NAMES_KEY_ID = " fiKeyID ";
public const string stFIELD_NAMES = stFIELD_NAMES_NO_KEY_ID + ", " + stFIELD_NAMES_KEY_ID;
Code:
//------------------------------
static private bool boCreateDatabaseTables(string stPathFilename,
string stUserID,
string stPassword,
List<string> liststTableNames,
List<string> liststFieldDefinitions)
{
bool boErrorFlag = false;
int iTablesCount = liststTableNames.Count();
string stOpenConn = new FbConnectionStringBuilder {
Database = stPathFilename,
UserID = stUserID,
Password = stPassword,
ServerType = FbServerType.Embedded,
ClientLibrary = stCLIENT_LIBRARY
}.ToString();
using (FbConnection fbConn = new FbConnection(stOpenConn)) {
try {
fbConn.Open();
FbTransaction fbTransaction = fbConn.BeginTransaction();
for (int ii = 0; ii < iTablesCount; ii++) {
string stSql = "CREATE TABLE " + liststTableNames[ii] + "( " + liststFieldDefinitions[ii] + ")";
FbCommand fbCmd = new FbCommand(stSql, fbConn, fbTransaction);
fbCmd.ExecuteNonQuery();
}
fbTransaction.Commit();
}
catch (Exception ex) {
boErrorFlag = true;
MessageBox.Show("catch ... GlobalsFirebird ... boCreateDatabaseTables ... " + ex.Message);
}
}
return boErrorFlag;
}//boCreateDatabaseTables
//------------------------------
//------------------------------
static public bool boAddRow(string stPathFilename,
string stUserID,
string stPassword,
string stTableName,
string stFieldNamesNoKeyId,
string stFieldNamesKeyId,
List<string> liststFieldValuesNoKeyId)
{
bool boErrorFlag = false;
string stOpenConn = new FbConnectionStringBuilder {
Database = stPathFilename,
UserID = stUserID,
Password = stPassword,
ServerType = FbServerType.Embedded,
ClientLibrary = stCLIENT_LIBRARY
}.ToString();
using(FbConnection fbConn = new FbConnection(stOpenConn)) {
fbConn.Open();
try {
string stValuesPlaceHolder = "#p0";
for (int iii = 1; iii < liststFieldValuesNoKeyId.Count; iii++)
stValuesPlaceHolder += ", #p" + (iii).ToString();
FbTransaction fbTransaction = fbConn.BeginTransaction();
string stCmd = "INSERT INTO " + stTableName + "(" + stFieldNamesNoKeyId + ") VALUES ( " + stValuesPlaceHolder + " ) RETURNING " + stFieldNamesKeyId;
FbCommand fbCmd = new FbCommand(stCmd, fbConn, fbTransaction);
for (int iii = 0; iii < liststFieldValuesNoKeyId.Count; iii++) {
string stPlaceHolder = "#p" + (iii).ToString();
string stValue = liststFieldValuesNoKeyId[iii];
fbCmd.Parameters.AddWithValue(stPlaceHolder, stValue);
}
fbCmd.Parameters.Add(new FbParameter() { Direction = System.Data.ParameterDirection.Output });
fbCmd.ExecuteNonQuery();
fbTransaction.Commit();
}
catch (Exception ex) {
boErrorFlag = true;
MessageBox.Show("catch ... GlobalsFirebird ... boAddRow ... " + ex.Message);
}
}
return boErrorFlag;
}//boAddRow
//------------------------------
I am building a simple Point of Sale program and working on a "search invoice" button that allows up to 3 search criteria (InvoiceID , ClientName, and ClientID). These are the names of 3 of the columns in the table named "Invoicing".
InvoiceID is the key column of type Int32, ClientName is of type String, ClientID is of type Int32. ClientName and ClientID searches work perfect.
MY PROBLEM: If I include InvoiceID in the select query, I get the following error. And I have spent a few days trying to figure it out.
ERROR: Database Error: Datatype mismatch in criteria expression.
Can you more experienced programmers help me out? thank you!
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data" + #" Source=TESTDB.accdb";
String tableName = "Invoicing";
String query = String.Format("select * from [{0}] where", tableName);
//ADD IN SEARCH CRITERIA
int filled = 0;
if (invoiceBox.Text != "") { query += " InvoiceID='" + invoiceBox.Text+"'"; filled += 1; }
/*if (DateCheckBox.Checked == true)
{
if (filled>=1) { query += " and DateNTime='" + monthCalendar1.SelectionStart.ToString() + "'"; filled += 1; }
else { query += " DateNTime='" + monthCalendar1.SelectionStart.ToString()+ "'"; filled += 1; }
}
* */
if (ClientNameBox.Text != "") //Doesnot work
{
if (filled >= 1) { query += " and Client='" + ClientNameBox.Text + "'"; filled += 1; }
else { query += " Client='" + ClientNameBox.Text + "'"; filled += 1; }
}
if (ClientIDBox.Text != "") //THIS search criteria works!!!!
{
if (filled >= 1) { query += " and ClientID='" + ClientIDBox.Text + "'"; filled += 1; }
else { query += " ClientID='" + ClientIDBox.Text + "'"; filled += 1; }
}
//CHECK IF SEARCH CRITERIA ARE PRESENT
if (filled < 1) { MessageBox.Show("At least One Search criteria above is required"); return; }
DataSet dsInvoicing = new DataSet();
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
//Open Database Connection
conn.Open();
OleDbDataAdapter daInvoicing = new OleDbDataAdapter(query, conn);
//Fill the DataSet
daInvoicing.Fill(dsInvoicing, tableName);
//MessageBox.Show("dsInventory has "+dsInventory.Tables[0].Rows.Count+" search results");
conn.Close();
this.dataGridView1.DataSource = dsInvoicing.Tables[0];
}
catch (OleDbException exp){ MessageBox.Show("Database Error: " + exp.Message.ToString());}
Need more information? I will post up more if I haven't provided enough.
DATABASE INFORMATION or other.
Thank you very much to all programmers.
Looks like the data type of InvoiceID in your database is some numeric kind. While in query you are treating it as string. Try not to wrap InvoiceID value in single quotes.
I have a function like this
///
/// This function binds the emplist drop down for mentor user.
///
private void BindEmpDropDownForMentor()
{
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
OleDbConnection oleConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand oleCommand = new OleDbCommand(strSelectMentorQuery, oleConnection);
try
{
//Open Connection
oleConnection.Open();
//Set Datasource and close connection
cmbempList.DataSource = oleCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
cmbempList.DataValueField = "";
cmbempList.DataTextField = "NAME";
//Bind the Dropdown
cmbempList.DataBind();
//Add a new item 'ALL TEAM MEMBERS' to the member list
cmbempList.Items.Insert(0, new ListItem("ALL TEAM MEMBERS", "0"));
cmbempList.SelectedIndex = 0;
GridViewDataShowBy = cmbempList.SelectedValue;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
}
finally
{
// Close the connection when done with it.
oleConnection.Close();
}
}
But on selected change event of cmbempList, format exception error is being caught saying this that input string was not in correct form in the bold line below
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
gvLeaveList.CurrentPageIndex = 0;
dgDaysAbsent.CurrentPageIndex = 0;
**if (!(Convert.ToInt32(cmbempList.SelectedValue) > 0))
{**
if (this.Session["RoleID"].ToString() == "1")
{
cmbLeads.ClearSelection();
cmbLeads.SelectedIndex = cmbLeads.Items.IndexOf(cmbLeads.Items.FindByValue(this.Session["UserID"].ToString()));
}
}
GridViewDataShowBy = cmbempList.SelectedValue.ToString();
if (cmbempList.SelectedValue != "0" && cmbempList.SelectedValue != "")
{
Page.Title = cmbempList.SelectedItem.Text + " | Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
else
{
Page.Title = "Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
PopulateLeaveList(GridViewDataShowBy, "0");
BindLeaveListGrid(GridViewDataShowBy, cmbLeads.SelectedValue.ToString());
}
It is because cmbempList's DataValueField is being set to an empty string in the BindEmpDropDownForMentor method.
cmbempList.DataValueField = "";
This will cause cmbempList's values to be bound to the values in the DataTextField which are strings. When the SelectedIndexChange event is called it tries to parse the strings to an Int32 which is throwing the exception.
Convert.ToInt32(cmbempList.SelectedValue) > 0
To fix it you can add an aliased ID field in the SQL query and set the cmbempList.DataValueField to that ID name which is probably your intent.
For example in BindEmpDropDownForMentor make this edit to your query:
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME, MLL.LED_ID AS ID FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
And assign your DataValueField to this:
cmbempList.DataValueField = "ID";
try this.
if it still fails look in the debugger what value cmbempList.SelectedValue contains.
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
// ...
object selectedValue = cmbempList.SelectedValue;
if ((selectedValue != null) && (selectedValue != DBNull.Value) && (!(Convert.ToInt32(selectedValue) > 0))
{
// ...