Mapping Error With DropDownList - c#

I am displaying categories in a dropdown list for adding products. When a product is to be added, you will have to select a category and Create Product or Update a previous product.
But my problem is that I get the following error:
No mapping exists from object type
System.Web.UI.WebControls.DropDownList to a known managed provider
native type.
Database Diagram:
ASPX.:
<p>Kategori</p>
<asp:DropDownList ID="DDCategories" runat="server" AutoPostBack="True">
</asp:DropDownList>
ASPX.CS.:
protected void Page_Load(object sender, EventArgs e)
{
//Dropdown Category Names From DB
if (!IsPostBack)
{
string sConstr = ConfigurationManager.ConnectionStrings["LLcateringConnectionString"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);
DataTable dt = new DataTable("tbl");
using (Conn)
{
Conn.Open();
SqlCommand comm = new SqlCommand("SELECT Name FROM Category", Conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
}
DDCategories.DataSource = dt;
DDCategories.DataTextField = "Name";
DDCategories.DataBind();
}
}
protected void BtnUpdateOrCreate_Click(object sender, EventArgs e)
{
// Text in fields has to exist, if they are requierd
if (!string.IsNullOrWhiteSpace(TxtName.Text) /*&&
!string.IsNullOrWhiteSpace(TxtDescription.Text)*/)
{
// New the DataAccess and have all the parameteres here
DataAccess dataAccess = new DataAccess();
dataAccess.AddParameter("#Name", TxtName.Text);
dataAccess.AddParameter("#Category_ID", DDCategories);
dataAccess.AddParameter("#Description", TxtDescription.Text.ToNewline(false));
dataAccess.AddParameter("#UnitPrice", TxtPrice.Text);
dataAccess.AddParameter("#DiscountUnitPrice", TxtUnitDiscount.Text);
if (isCreate)
{
// Insert query
dataAccess.Execute(#"INSERT INTO [Product] ([Name], [Category_ID], [UnitPrice], [DiscountUnitPrice], [Description])
VALUES (#Name, #Category_ID, #UnitPrice, #DiscountUnitPrice, #Description)
INNER JOIN dbo.Product ON dbo.Category.ID = dbo.Product.Category_ID
ORDER BY [Name]
WHERE id = #id");
}
else
{
// Update query
dataAccess.AddParameter("#id", MenuID);
dataAccess.Execute(#"UPDATE [Product]
SET [Name] = #Name, [Category_ID] = #Category_ID, [UnitPrice] = #UnitPrice, [DiscountUnitPrice] = #DiscountUnitPrice, [Description] = #Description
WHERE id = #id");
//UPDATE [Product]
//SET [Name] = #Name, [Category_ID] = #Category_ID, [UnitPrice] = #UnitPrice, [DiscountUnitPrice] = #DiscountUnitPrice, [Description] = #Description
//INNER JOIN dbo.Product ON dbo.Category.ID = dbo.Product.Category_ID
//ORDER BY [Name]
//WHERE id = #id");
}
// Redirects to list
Response.Redirect(Request.Url.AbsolutePath);
}
else
LitStatus.Text = "Hey så indtast da noget!";
}

check this line
dataAccess.AddParameter("#Category_ID", DDCategories);
and replace with
dataAccess.AddParameter("#Category_ID", DDCategories.SelectedValue)

Related

How to query and assign timeslots with daypilot c#

I'm using ASP.NET daypilot event calendar
Data is stored in a SQLite File for testing
The Events in the Calendar have the following structure
CREATE TABLE event (
id VARCHAR(50),
name VARCHAR(50),
eventstart DATETIME,
eventend DATETIME
);
my tables
objects(Id,Name)
timeprofiles(Id,Object.Id,Location.Id,Start,End)
locations(Id,Name,Addr)
Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek(new DateTime(2020, 1, 1));
DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days);
DataBind();
}
}
CalendarEventMove
protected void DayPilotCalendar1_EventMove(object sender, DayPilot.Web.Ui.Events.EventMoveEventArgs e)
{
dbUpdateEvent(e.Value, e.NewStart, e.NewEnd);
DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days);
DayPilotCalendar1.DataBind();
DayPilotCalendar1.Update();
}
LoadingEvents
private DataTable dbGetEvents(DateTime start, int days)
{
SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT [id], [name], [eventstart], [eventend] FROM [event] WHERE NOT (([eventend] <= #start) OR ([eventstart] >= #end))", ConfigurationManager.ConnectionStrings["db"].ConnectionString);
da.SelectCommand.Parameters.AddWithValue("start", start);
da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days));
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
UpdateEvents
private void dbUpdateEvent(string id, DateTime start, DateTime end)
{
using (SQLiteConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand("UPDATE [event] SET [eventstart] = #start, [eventend] = #end WHERE [id] = #id", con);
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters.AddWithValue("start", start);
cmd.Parameters.AddWithValue("end", end);
cmd.ExecuteNonQuery();
}
}
I'm trying filter this by location, adding a combobox to select and then querying by location
Does someone have an idea how to achieve this?

Data not Saving in Database after Creating (CRUD)

I am working on simple CRUD application where I have two tables:
Patient
CNIC (varchar 50 and PK)
Name (varchar 50)
PatientVaccines
Cnic (varchar 50 and FK)
VaccinationName (varchar)
VaccinationDate (varchar)
CenterAddress (varchar)
I know making string as PK, FK is not a good approach but this is my requirement.
I have a PatientDBContext class where I perform CRUD operations:
public class PatentDBContext
{
string cs = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
public List<Patient> getPatients()
{
List<Patient> PatientList = new List<Patient>();
SqlConnection con = new SqlConnection(cs);
string query = "SELECT p.CNIC, p.Name, pv.cnic, pv.VaccinationName, pv.VaccinationDate, pv.CenterAddress FROM Patient AS p JOIN PatientVaccines AS pv ON p.CNIC = pv.cnic";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Patient p = new Patient();
p.CNIC = dr["CNIC"].ToString();
p.Name = dr["Name"].ToString();
p.VaccinationName = dr["VaccinationName"].ToString();
//p.VaccinationDate = dr["VaccinationDate"].ToString();
p.CentreAddress = dr["CenterAddress"].ToString();
PatientList.Add(p);
}
con.Close();
return PatientList;
}
public bool AddPatient(Patient pat)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand("spAddPatient", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CNIC", pat.CNIC);
cmd.Parameters.AddWithValue("#Name", pat.Name);
cmd.Parameters.AddWithValue("#VaccinationName", pat.VaccinationName);
cmd.Parameters.AddWithValue("#VaccinationDate", pat.VaccinationDate);
cmd.Parameters.AddWithValue("#CenterAddress", pat.CentreAddress);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
return true;
}
else
{
return false;
}
}
public bool UpdatePatient(Patient pat)
{
SqlConnection con = new SqlConnection();
string query = "UPDATE PatientVaccines SET VaccinationName = #VaccinationName, VaccinationDate = #VacinationDate, CenterAddress = #CenterAddress WHERE Cnic = #Cnic";
SqlCommand cmd = new SqlCommand(query, con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CNIC", pat.CNIC);
//cmd.Parameters.AddWithValue("#Name", pat.Name);
cmd.Parameters.AddWithValue("#VaccinationName", pat.VaccinationName);
cmd.Parameters.AddWithValue("#VaccinationDate", pat.VaccinationDate);
cmd.Parameters.AddWithValue("#CenterAddress", pat.CentreAddress);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
return true;
}
else
{
return false;
}
}
}
Errors is this class is in getPatient() function I comment it out p.VaccinationDate that shows an error that I cannot convert implicitly type string to DateTime, how do I convert it to DateTime?
I have another function names AddPatient()that now show any error or bug but when I click submit button after input records it doesn't perform any action.
HomeController
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
PatentDBContext db = new PatentDBContext();
List<Patient> obj = db.getPatients();
return View(obj);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Patient pat)
{
try
{
if (ModelState.IsValid == true)
{
PatentDBContext context = new PatentDBContext();
bool check = context.AddPatient(pat);
if (check == true)
{
TempData["InsertMessage"] = "Data Inserted..";
}
else
{
TempData["FailureMessage"] = "Data Not Inserted";
}
ModelState.Clear();
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
public ActionResult Edit(string Cnin)
{
PatentDBContext context = new PatentDBContext();
//string str = Cnin.ToString();
var row = context.getPatients().Find(model => model.CNIC = Cnin);
return View(row);
}
}
Here I also can't convert implicitly type string to bool
var row = context.getPatients().Find(model => model.CNIC = Cnin);
and finally this is my stored procedure:
ALTER PROCEDURE [dbo].[spAddPatient]
(#CNIC varchar(50),
#Name varchar(50),
#VaccinationName varchar(50),
#VaccinationDate varchar(50),
#CenterAddress varchar(50))
AS
BEGIN
INSERT INTO Patient (CNIC, Name)
VALUES (#CNIC, #Name)
INSERT INTO PatientVaccines (Cnic, VaccinationName, VaccinationDate, CenterAddress)
VALUES (#Cnic, #VaccinationName, #VaccinationDate, #CenterAddress)
END
I pretty sure that you are very new in this technology as there are some basic mistake. I am mentioning some common mistake below:
You should not use varchar as primary key instead use int
Make a relation in both parent and child table using int column.
Do not use varchar for date field, instead use DateTime.
I redesigned two tables as below:
Patient Table
CREATE TABLE [dbo].[Patient](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CNIC] [varchar](50) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
I introduce new column Id that set as IDENTITY so that this
column will get value automatically like 1, 2, 3
PatientVaccines Table
CREATE TABLE [dbo].[PatientVaccines](
[Id] [int] IDENTITY(1,1) NOT NULL,
[VaccinationName] [varchar](50) NULL,
[VaccinationDate] [datetime] NULL,
[CenterAddress] [varchar](50) NULL,
[PatientId] [int] NOT NULL,
CONSTRAINT [PK_PatientVaccines] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
I introduce two new columns Id and PatientId. when you insert a patient, the Id field will get a number automaticaly and that id will be inserted into PatientVaccines Table as PatientId so that you can find the relational data. Also I used datetime for VaccinationDate.
FOREIGN KEY CONSTRAINT
ALTER TABLE [dbo].[PatientVaccines] WITH CHECK ADD CONSTRAINT [FK_PatientVaccines_Patient] FOREIGN KEY([PatientId])
REFERENCES [dbo].[Patient] ([Id])
This is a constraint or rules that will restrict you to insert data that is not relational. for example: you do not have a record of patient with Id 101 but you are trying to insert PatientVaccines record with PatientId 101 then this rule will restrict you to do that.
Here is the Sql Diagram of Two tables
By doing the above, you need to update your Stored Procedure as below:
CREATE PROCEDURE [dbo].[spAddPatient]
(#CNIC varchar(50),
#Name varchar(50),
#VaccinationName varchar(50),
#VaccinationDate datetime,
#CenterAddress varchar(50))
AS
BEGIN
INSERT INTO Patient (CNIC, Name)
VALUES (#CNIC, #Name)
INSERT INTO PatientVaccines (PatientId, VaccinationName, VaccinationDate, CenterAddress)
VALUES (##Identity, #VaccinationName, #VaccinationDate, #CenterAddress)
END
Here is the complete C# Code where I made some correction
public class PatentDBContext
{
string cs = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
public List<Patient> getPatients()
{
List<Patient> PatientList = new List<Patient>();
SqlConnection con = new SqlConnection(cs);
string query = "SELECT p.CNIC, p.Name, pv.VaccinationName, pv.VaccinationDate, pv.CenterAddress FROM Patient AS p JOIN PatientVaccines AS pv ON p.Id = pv.PatientId";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Patient p = new Patient();
p.CNIC = dr["CNIC"].ToString();
p.Name = dr["Name"].ToString();
p.VaccinationName = dr["VaccinationName"].ToString();
p.VaccinationDate = Convert.ToDateTime(dr["VaccinationDate"]);
p.CenterAddress = dr["CenterAddress"].ToString();
PatientList.Add(p);
}
con.Close();
return PatientList;
}
public bool AddPatient(Patient pat)
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("spAddPatient", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CNIC", pat.CNIC);
cmd.Parameters.AddWithValue("#Name", pat.Name);
cmd.Parameters.AddWithValue("#VaccinationName", pat.VaccinationName);
cmd.Parameters.AddWithValue("#VaccinationDate", pat.VaccinationDate);
cmd.Parameters.AddWithValue("#CenterAddress", pat.CenterAddress);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
return true;
}
else
{
return false;
}
}
public bool UpdatePatient(Patient pat)
{
SqlConnection con = new SqlConnection(cs);
string query = "UPDATE PatientVaccines SET VaccinationName = #VaccinationName, VaccinationDate = #VaccinationDate, CenterAddress = #CenterAddress WHERE PatientId = ( Select Id from Patient where Cnic = #Cnic)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#CNIC", pat.CNIC);
//cmd.Parameters.AddWithValue("#Name", pat.Name);
cmd.Parameters.AddWithValue("#VaccinationName", pat.VaccinationName);
cmd.Parameters.AddWithValue("#VaccinationDate", pat.VaccinationDate);
cmd.Parameters.AddWithValue("#CenterAddress", pat.CenterAddress);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
return true;
}
else
{
return false;
}
}
}
I believe your stored procedure is not correct, you can test it beforehand in the database.
// here you should use operator== instead of аssignment operator=
// Have in mind that .Find will throw an error if model with given Cnin is not found
var row = context.getPatients().Find(model => model.CNIC == Cnin);
How to convert a string to datetime object
Create a stored procedure
General advice, you can google the errors you get and find information about them

SQL dependency C#

I am looking to have live data on UI table, I want to get the data from a SQL Server stored procedure that uses a table valued function but I get an invalid subscription error when the dependency change is called.
SqlConnection co = new SqlConnection(_connectionStringTest);
var messages = new List<WorkToListHeaderModel>();
SqlDependency.Stop(_connectionStringTest);
SqlDependency.Start(_connectionStringTest);
using (var cmd = new SqlCommand(#"[DBO].[spTest]", co))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
SqlDataAdapter da = new SqlDataAdapter(cmd);
var dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
messages.Add(item: new WorkToListHeaderModel
{
SalesOrderNumber = ds.Tables[0].Rows[i][0].ToString(),
});
}
}
return messages;
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MyHub.SendMessages();
}
}
The SQL
ALTER PROCEDURE [dbo].[spTest]
AS
BEGIN
SELECT SalesOrderNumber, Test
FROM dbo.[TableTest]('z')
END
Function
ALTER FUNCTION [dbo].[TableTest]
(#SalesOrderNumber NVARCHAR(100))
RETURNS
#Table TABLE
(
SalesOrderNumber NVARCHAR(100),
Test NVARCHAR(150)
)
AS
BEGIN
;WITH Selects AS
(
SELECT
AdamTest.SalesOrderNumber,
TEST AS CustomerName
FROM
[dbo].[Test]
LEFT JOIN
DBO.Test2 ON Test2.SALESORDERNUMBER = Test.SalesOrderNumber
)
INSERT INTO #Table
SELECT DISTINCT s.SalesOrderNumber, s.CustomerName
FROM Selects AS S
RETURN

Invalid columns names Insert statement

I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.
That is the error that I get:
Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.
Can you help me? I think the problem is in the insert statement
Thanks
public void userSales()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
userSales();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
userSales();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
cmd.Parameters.AddWithValue("#Activity_ID", txtActivity.Text.Trim());
cmd.Parameters.AddWithValue("#Date", ftxtDate.Text.Trim());
cmd.Parameters.AddWithValue("#Quotation_Number", ftxtQno.Text.Trim());
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Quantity", ftxtQuantity.Text.Trim());
cmd.Parameters.AddWithValue("#valueGBR", ftxtvalueGBR.Text.Trim());
cmd.Parameters.AddWithValue("#valueEUR", ftxtvalueEUR.Text.Trim());
cmd.Parameters.AddWithValue("#weightedValue",ftxtweightedValue.Text.Trim());
cmd.Parameters.AddWithValue("#Rate", ftxtRate.Text.Trim());
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#estDecisionDate", ftxtestDecisionDate.Text.Trim());
cmd.Parameters.AddWithValue("#PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userSales();
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+'Sale Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+' Sale Details not inserted');</script>");
}
}
}
Your Select Statement is executing this...
SELECT SalesActivity.Activity_ID
,SalesActivity.DATE
,SalesActivity.Quatation_Number
,CUSTOMER.Customer_Name
,PRODUCTS.Machine_Model
,SalesActivity.Quantity
,SalesActivity.valueGBR
,SalesActivity.valueEUR
,SalesActivity.Rate
,SalesActivity.weightedValue
,STATUS.STATUS
,SalesActivity.estDecisionDate
,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID
Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.
change this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
to this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #estDecisionDate, #PromisedDeliveryDate)", con);
and remove the following lines...
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
The insert should now work.

How to get ID of the Last Inserted Record in SQL using ASP.net

Here is my code
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
string clientId = Context.User.Identity.GetUserId();
if (clientId != null)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
customize1 customize = new customize1
{
client_id = clientId,
product_id = id,
paper_type = Labelpt.Text,
corner = Labelpc.Text,
shipping_type = Labelsp.Text,
text = TextBox3.Text,
amount = Convert.ToInt32(lbResult.Text)
};
customizeModel model = new customizeModel();
Label9.Text = model.Insertcustomize(customize);
con.Open();
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "select top 1 * from customize1 where client_id='"+clientId+"' order by Id desc ";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
customizeid = dr2["Id"].ToString();
}
con.Close();
}
}
}
I need the last row id but my query does not generate any value.I also check my query in SSMS and query is working fine but in asp it is not generating any data and for inserting record i used the concept of class and entity relationship.
Any Solution.
Brother there are two ways:
One is when you insert your row place after the Insert query this:
SELECT SCOPE_IDENTITY()
For example:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
SELECT SCOPE_IDENTITY()
It gives the inserted ID back.
The second way is this query;
SELECT id FROM table ORDER BY id DESC LIMIT 1
If you keep struggling with problems be open to ask more.

Categories