textbox value to database - textbox

I have two forms, when I click my button, it must add the values of the textboxes to the database and display it in the second form "Debtors".
The problem I'm having, is that I'm not getting the "Debtors" to capture the data in the datagrid.
private void DebAddBut_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\simeo\source\repos\SparesPOS\SparesPOS\PartsPosDB.mdf;Integrated Security=True";
StringBuilder strSQL = new StringBuilder();
strSQL.Append("Insert into DebtorData values(");
strSQL.Append("#DebtorID, #DebtorName,#DebtorPhone1,#DebtorPhone2,");
strSQL.Append("#DebtorFax,#DebtorEmail,#DebtorAddr1,#DebtorAddr2,");
strSQL.Append("#DebtorAddr3,#DebtorAddr4,#DebtorPostCode,#DebtorContact1,");
strSQL.Append("#DebtorContact2,#DebtorLimit)");
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("#DebtorID", SqlDbType.Int).Value = DebIDtxt.Text;
cmd.Parameters.Add("#DebtorName", SqlDbType.VarChar, 50).Value = DebNametxt.Text;
cmd.Parameters.Add("#DebtorPhone1", SqlDbType.VarChar, 50).Value = DebPh1txt.Text;
cmd.Parameters.Add("#DebtorPhone2", SqlDbType.VarChar, 50).Value = DebPh2txt.Text;
cmd.Parameters.Add("#DebtorFax", SqlDbType.VarChar, 50).Value = DebFaxtxt.Text;
cmd.Parameters.Add("#DebtorEmail", SqlDbType.VarChar, 50).Value = DebEmtxt.Text;
cmd.Parameters.Add("#DebtorAddr1", SqlDbType.VarChar, 50).Value = DebAdr1txt.Text;
cmd.Parameters.Add("#DebtorAddr2", SqlDbType.VarChar, 50).Value = DebAdr2txt.Text;
cmd.Parameters.Add("#DebtorAddr3", SqlDbType.VarChar, 50).Value = DebAdr3txt.Text;
cmd.Parameters.Add("#DebtorAddr4", SqlDbType.VarChar, 50).Value = DebAdr4txt.Text;
cmd.Parameters.Add("#DebtorPostCode", SqlDbType.VarChar, 50).Value = debPosCtxt.Text;
cmd.Parameters.Add("#DebtorContact1", SqlDbType.VarChar, 50).Value = DebCont1txt.Text;
cmd.Parameters.Add("#DebtorContact2", SqlDbType.VarChar, 50).Value = DebCont2txt.Text;
cmd.Parameters.Add("#DebtorLimit", SqlDbType.VarChar, 50).Value = DebLimittxt.Text;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSQL.ToString();
cmd.Connection = sqlConn;
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch { }
}
Debtors form = new Debtors();
form.Refresh();
form.Show();
}

Related

How to Populate DropDownList from the Database in MVC

I am new to ASP NET MVC
I need Populate a drop down list from values obtained from a database table using MySql database and view model, after checking if the current user is application enabled, using ASP NET MVC.
This is the tutorial
My code below return
Error: returns void, a return keyword must not be followed by an object expression
On this line
return items;
Any help really appreciated.
Controller
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
List<SelectListItem> items = new List<SelectListItem>();
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "' ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
connection.Close();
}
}
return items;
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
Update
I have tried with this code.
I have error
Error CS0103 The name 'cCountry' does not exist in the current context
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
TempData["Dates"] = PopulateDates();
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
private static List<SelectListItem> PopulateDates()
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "'; ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
You are not passing cCountry value to populateDates.That's why you are getting this error. You can do something like below to get drop down populated. However it is not good idea to write Business Logic directly in controller. You should move it to model or Business layer.
private static List<SelectListItem> PopulateDates(string country)
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM dotable_countries WHERE cCountry = #country";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("#country",country);
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
and while calling this method in Action pass country value to it like below
TempData["Dates"] = PopulateDates(cCountry);

Get multiple nested partial views in MVC

I have one page which contains one multiple partial pages. In each partial view there will be again multiple partial pages. When I am getting this, it will add data table to ds contains three tables. How can I show it in hierarchical order?
In my ds three tables come from DB shows particular record. How can I display this?
THis is my DAL:
public static ConsignmentNote GetConsignmentNoteByID(int id)
{
ConsignmentNote consignmentnote = null;
SqlConnection sqlConnection = null;
sqlConnection = SqlConnectionHelper.GetConnectionConnectionString();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
cmd = new SqlCommand("GetConsignmentNoteByCNNoteId", sqlConnection);
cmd.Parameters.Add(new SqlParameter("#ConsignmentNoteID", id));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(ds);
//First table data
if (ds.Tables[0].Rows.Count > 0)
{
DataRow row = ds.Tables[0].Rows[0];
consignmentnote = new ConsignmentNote(row);
}
else
{
consignmentnote = new ConsignmentNote();
}
//Second table data
consignmentnote.LstAdditionalCN = new List<AdditionalCN>();
int rowIndexCN = 1;
if (ds.Tables[1].Rows.Count > 0)
{
int i = 0;
foreach (DataRow acnRow in ds.Tables[i].Rows)
{
AdditionalCN objACN = new AdditionalCN();
objACN.ConsignmentNoteRelID = acnRow["ConsignmentNoteRelID"] as Int32? ?? 0;
objACN.ConsignmentNoteID = acnRow["ConsignmentNoteID"] as Int32? ?? 0;
objACN.ConsignmentNoteNumber = acnRow["ConsignmentNoteNumber"] as string ?? null;
objACN.CNDate = acnRow["CNDate"] as DateTime? ?? DateTime.MinValue;
objACN.ConsignerID = (acnRow["ConsignerID"] as Int32? ?? 0).ToString();
objACN.ConsigneeID = (acnRow["ConsigneeID"] as Int32? ?? 0).ToString();
objACN.LocationFrom = acnRow["LocationFrom"] as string ?? null;
objACN.LocationTo = acnRow["LocationTo"] as string ?? null;
if (rowIndexCN == 1)
{
//insert to default CNI
consignmentnote.ConsignmentNoteRelID = objACN.ConsignmentNoteRelID;
consignmentnote.ConsignmentNoteNumber = objACN.ConsignmentNoteNumber;
}
else
{
//insert to additional CNI
consignmentnote.LstAdditionalCN.Add(objACN);
}
rowIndexCN++;
}
}
consignmentnote.LstAdditionalInvoice = new List<AdditionalInvoice>();
int rowIndexCNInvoice = 1;
if (ds.Tables[2].Rows.Count > 0)
{
foreach (DataRow acnRow in ds.Tables[2].Rows)
{
AdditionalInvoice objACN = new AdditionalInvoice();
objACN.ConsignmentNoteLineItemID = acnRow["ConsignmentNoteLineItemID"] as Int32? ?? 0;
objACN.ConsignmentNoteID = acnRow["ConsignmentNoteID"] as Int32? ?? 0;
objACN.ConsignmentNoteRelID = acnRow["ConsignmentNoteRelID"] as Int32? ?? 0;
objACN.ProjectPO = (acnRow["ProjectPO"] as Int32? ?? 0).ToString();
objACN.InvoiceNum = (acnRow["InvoiceNum"] as Int32? ?? 0).ToString();
objACN.InvoiceDate = acnRow["InvoiceDate"] as DateTime? ?? DateTime.MinValue;
objACN.Pkgs = acnRow["Pkgs"] as string ?? null;
objACN.Description = acnRow["Description"] as string ?? null;
objACN.ActualWeight = acnRow["ActualWeight"] as string ?? null;
objACN.ChargedWeight = acnRow["ChargedWeight"] as string ?? null;
objACN.InvoiceValue = acnRow["InvoiceValue"] as decimal? ?? 0;
if (rowIndexCNInvoice == 1)
{
//insert to default CNI
consignmentnote.ConsignmentNoteRelID = objACN.ConsignmentNoteRelID;
consignmentnote.ConsignmentNoteID = objACN.ConsignmentNoteID;
}
else
{
//insert to additional CNI
consignmentnote.LstAdditionalInvoice.Add(objACN);
}
rowIndexCNInvoice++;
}
}
}
catch (Exception x)
{
throw x;
}
finally
{
}
return consignmentnote;
}

exception occurence in mvc

****I am getting an exception of type 'System.IndexOutOfRangeException' in System.Data.dll but was not handled in user code****
public List<ItemModel> med()
{
List<ItemModel> itemList = new List<ItemModel>();
connection();
SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PstrOperationFlag", "S-drugname");
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
ItemModel item = new ItemModel();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
ItemModel io = new ItemModel();
while (sdr.Read())
{
io = new ItemModel();
io.medication = sdr["medications"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
}
Try this
public List<ItemModel> med()
{
List<ItemModel> itemList = new List<ItemModel>();
ItemModel io;
connection();
SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PstrOperationFlag", "S-drugname");
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
io = new ItemModel();
io.medication = sdr["medications"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}

I am getting an error at get property with error 'BusinessLayer.EmployeeBusinessLayer.Employees.get': not all code paths return a value

I am getting an error at get property that not all code paths return a value.
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get // Here i am getting an error that not all code paths return a value
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.Emp_Name = Convert.ToString(rdr["Emp_Name"]);
employee.Designation = Convert.ToString(rdr["Designation"]);
employee.City = Convert.ToString(rdr["City"]);
employee.State = Convert.ToString(rdr["State"]);
employee.Country = Convert.ToString(rdr["Country"]);
employees.Add(employee);
}
}
}
}
}
}
The error message can be taken literally:
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get // Here i am getting an error that not all code paths return a value
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.Emp_Name = Convert.ToString(rdr["Emp_Name"]);
employee.Designation = Convert.ToString(rdr["Designation"]);
employee.City = Convert.ToString(rdr["City"]);
employee.State = Convert.ToString(rdr["State"]);
employee.Country = Convert.ToString(rdr["Country"]);
employees.Add(employee);
}
}
return employees;
}
}
}
}
Need to return your employees. Also you should Close() and dispose your reader.
using(IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
...
employees.Add(employee);
}
rdr.Close();
}
return employees;

How to fill dropdownlist in MVC-4 using dapper

I filled Drop Down List in MVC which is working fine but now I want to do it using Dapper but got stuck.
DropDownList in MVC without Dapper
Controller
[HttpPost]
public ActionResult Create(User ur)
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
ModelState.Clear();
FillCountry();
}
public void FillCountry()
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "select * from tbl_country ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
while (rdr.Read())
{
li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
}
ViewData["country"] = li;
}
View
#{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new {onchange = "this.form.submit();" })
#{ Html.EndForm(); }
This is what I am trying to do now
DropDownList in MVC with Dapper
Model
public class Region
{
private int _CountryId;
private string _CountryName;
public int CountryId
{
get { return _CountryId; }
set { _CountryId = value; }
}
public string CountryName
{
get { return _CountryName; }
set { _CountryName = value; }
}
Controller
[HttpPost]
public ActionResult AddMobiles(TBMobileDetails MD, HttpPostedFileBase file)
{
FileUpload(file);
MobileMain MM = new MobileMain();
MM.AddMobiles(MD);
FillCountry();
return RedirectToAction("AllMobileList");
}
Stuck in this part how to fill it using dapper? How to populate my list?
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
}
View
#{ Html.BeginForm("AddMobiles", "AddMobile", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }
You are passing in ViewData["country"] object of type IEnumerable<Region> while in View you are casting it to IEnumerable<SelectListItem> which won't work obviously in action change FillCountry() to make SelectList:
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
var list = new SelectList(result,"CountryId","CountryName");
}
and in View now cast it to SelectList:
#Html.DropDownList("country", ViewData["country"] as SelectList, new {onchange = "this.form.submit();" })
This will get you going.

Resources