I am struggling a bit to populate my dropdown list, can anybody tell me where I am going wrong?
ASPX CODE it keeps looping after getting the connection string - back into the connection string method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private string GetConnectionString()
{
using (DataManager dmgr = new DataManager())
{
dmgr.Connect(ConfigurationManager.AppSettings["ProductionKey"]);
return BindDropDownList();
}
}
public string BindDropDownList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Itemseriesmaster";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Description"; // the items to be displayed in the list items
DropDownList1.DataValueField = "ID"; // the id of the items displayed
DropDownList1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return AppRelativeTemplateSourceDirectory;
}
DataManager Code - where the code calls into
public DataSet ItemSeriesMaster(int id, string description)
{
object[] args = new object[2] { id, description };
return CallSp(MethodBase.GetCurrentMethod(), args) as DataSet; // i know this is not an sp call.. just testing
}
}
}
I am trying to go to my database and bring out the list.
I am doing a web application in asp.net.
I have a class CommonDB to save data.
public class CommonDB
{
private static string GetConnectionString = ConfigurationManager.ConnectionStrings["Db"].ToString();
public static SqlConnection GetConnection()
{
SqlConnection Con = new SqlConnection(GetConnectionString);
if (Con.State == ConnectionState.Open)
{
Con.Close();
}
return Con;
}
public static int ExecuteNonquery(SqlCommand cmd)
{
SqlConnection Con = GetConnection();
Con.Open();
try
{
cmd.Connection = Con;
Con.Close();
return ReturnVal;
}
catch
{
Con.Close();
return 0;
}
}
}
}
I am using the following function to save data
public int AddGroupMaster() //Inserting
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "NV_Group_Master_Add";
cmd.Parameters.AddWithValue("#Group_ID", iGroupId);
cmd.Parameters.AddWithValue("#Group_Code", strGroupName);
cmd.Parameters.AddWithValue("#Group_Name", strGroupName);
cmd.Parameters.AddWithValue("#Created_On", strCreatedOn);
cmd.Parameters.AddWithValue("#Modified_On", strModifiedOn);
iReturn = CommonDB.ExecuteNonquery(cmd);
return iReturn;
}
catch { return 0; }
}
This function is called from code behind like :
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
objGroup.strGroupName = txtGroupName.Text.Trim();
objGroup.strCreatedOn = DateTime.Today.ToString();
objGroup.strModifiedOn = "";
objGroup.AddGroupMaster();
}
catch
{
}
}
I want to use Commit and rollback. How it is possible in my coding??
Please suggest a solution
In your scenario, you will have to do that in your CommonDB library.
For example, your ExecuteNonQuery method would look like this:
public static int ExecuteNonquery(SqlCommand cmd) {
int retVal;
SqlConnection Con = GetConnection();
DbTransaction tran;
try {
cmd.Connection = Con;
cmd.Connection.Open();
tran = cmd.Connection.BeginTransaction;
cmd.Transaction = tran;
retVal = cmd.ExecuteNonQuery;
tran.Commit()
} catch {
tran.Rollback();
throw;
} finally {
cmd.Connection.Close()
}
return retVal;
}
And yes, do not forget to get a reference to System.Data.Common.
The following code i have used in web form and i want to convert it into asp.net mvc4 with four buttons and their events and grid.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MasterFiles
{
public partial class WebForm1 : System.Web.UI.Page
{
//This is the connection string
public static String connstr = "Data Source=23.22.136.160;Initial Catalog=Medcare;Persist Security Info=True;User ID=sa;Password=dlink";
//This is common method to bind the drop downs
public static void FillDDList(ref DropDownList DropDownName, String Query)
{
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
SqlDataReader dr;
try
{
//Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
SqlCommand cmd = new SqlCommand(Query, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListItem extLI = new ListItem();
extLI.Value = dr[0].ToString();
extLI.Text = dr[1].ToString();
DropDownName.Items.Add(extLI);
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
con.Close();
//RunCustomScript("alert('" + ex.Message.ToString() + "')", callingPageObjectName);
}
}
}
//This is the method to bind the grid.
public static bool FillGridBySqlString(ref System.Web.UI.WebControls.GridView GVW, string strSQL)
{
SqlConnection conn = new SqlConnection();
System.Data.SqlClient.SqlCommand SqlComm1 = new System.Data.SqlClient.SqlCommand();
DataSet ds = new DataSet();
DataTable dt_Kit = new DataTable();
//DataTable dt_Items = new DataTable();
SqlDataAdapter ListAdapter = new SqlDataAdapter();
conn.ConnectionString = connstr;
SqlCommand dataSelectCommand = new SqlCommand();
dataSelectCommand.CommandType = CommandType.Text;
dataSelectCommand.CommandText = strSQL;
dataSelectCommand.CommandType = System.Data.CommandType.Text;
dataSelectCommand.Connection = conn;
ListAdapter.SelectCommand = dataSelectCommand;
ListAdapter.Fill(dt_Kit);
dt_Kit.TableName = "Kit";
ds.Tables.Add(dt_Kit);
GVW.DataSource = ds;
GVW.DataMember = "Kit";
GVW.DataBind();
try
{
dt_Kit.Clear();
ds.Tables.Remove(dt_Kit);
ds.Clear();
}
catch
{
}
return true;
}
//This is the method to execute the sql command.
public static void execNonQuerySQL(string sql)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
DataSet ds = new DataSet();
SqlCommand dataSelectCommand = new SqlCommand();
try
{
dataSelectCommand.CommandType = CommandType.Text;
dataSelectCommand.CommandText = sql;
dataSelectCommand.Connection = conn;
conn.Open();
dataSelectCommand.ExecuteNonQuery();
}
catch { }
conn.Close();
dataSelectCommand.Dispose();
}
public static void execNonQuerySSP(string StoredProcName, Object[,] parmarr)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
DataSet ds = new DataSet();
SqlCommand dataSelectCommand = new SqlCommand();
try
{
dataSelectCommand.CommandType = CommandType.StoredProcedure;
dataSelectCommand.CommandText = StoredProcName;
dataSelectCommand.Connection = conn;
conn.Open();
for (int i = 0; i < parmarr.Length / 2; )
{
dataSelectCommand.Parameters.AddWithValue("#" + parmarr[i, 0], parmarr[i, 1]);
if (parmarr[i++, 0] == null) break;
}
dataSelectCommand.ExecuteNonQuery();
}
catch { }
conn.Close();
dataSelectCommand.Dispose();
}
string sqlstr = "select " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Medcare.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'VMGR' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Base Data in VM/Medcare], " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Pils.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'PILS' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Mapped Data in PILS System], " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Alg.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'ALG' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Mapped Data in ALG System], " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Boise1.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'USI' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Mapped Data in USI System] " +
" from MasterCodesMap A where MCM_APP_ACRO = 'VMGR' " +
" Order by 2 ";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDDList(ref DropDownList1, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from Medcare.dbo.Billing_Code Order by 1");
FillDDList(ref DropDownList2, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from PILS.dbo.Billing_Code Order by 1");
FillDDList(ref DropDownList3, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from ALG.dbo.Billing_Code Order by 1");
FillDDList(ref DropDownList4, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from Boise1.dbo.Billing_Code Order by 1");
FillGridBySqlString(ref GridView1, sqlstr);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Set the hand mouse cursor for the selected row.
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor = 'hand';");
//////// The seelctButton exists for ensuring the selection functionality
//////// and bind it with the appropriate event hanlder.
//////LinkButton selectButton = new LinkButton()
//////{
////// CommandName = "Select",
////// Text = e.Row.Cells[0].Text
//////};
//////selectButton.Font.Underline = false;
//////selectButton.ForeColor = System.Drawing.Color.Beige;
//////e.Row.Cells[3].Controls.Add(selectButton);
////////e.Row.Attributes["OnClick"] =
//////// Page.ClientScript.GetPostBackClientHyperlink(selectButton, "");
//////e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(DropDownList1.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "VMGR" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList1.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap",parmarr);
}
if (DropDownList2.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "PILS" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList2.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap", parmarr);
}
if (DropDownList3.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "ALG" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList3.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap", parmarr);
}
if (DropDownList4.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "USI" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList4.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap", parmarr);
}
FillGridBySqlString(ref GridView1, sqlstr);
}
protected void Button2_Click(object sender, EventArgs e)
{
execNonQuerySQL("delete MasterCodesMap where MCM_VM_ID = " + DropDownList1.SelectedValue);
FillGridBySqlString(ref GridView1, sqlstr);
}
protected void Button3_Click(object sender, EventArgs e)
{
Object[,] parmarr = {
{ "iVM_ID", DropDownList1.SelectedValue},
{ "iTABLE_ACRO", "BLCD"}
};
execNonQuerySSP("synchVMMasterData", parmarr);
FillGridBySqlString(ref GridView1, sqlstr);
}
protected void Button4_Click(object sender, EventArgs e)
{
FillGridBySqlString(ref GridView1, sqlstr);
}
}
}
you can pass your data for dropdownlist by ViewBag:
ViewBag.ProfileId = new SelectList(db.UserProfiles, "Id", "Username");
and get in your view :
#Html.DropDownList("ProfileId", String.Empty)
or another example :
Controller
public ActionResult Index()
{
List<SelectListItem> obj1 = new List<SelectListItem>();
obj1.Add(new SelectListItem { Text = "Text1", Value = "1" });
obj1.Add(new SelectListItem { Text = "Text2", Value = "2" });
obj1.Add(new SelectListItem { Text = "Text3", Value = "3" });
List<SelectListItem> obj2 = new List<SelectListItem>();
obj2.Add(new SelectListItem { Text = "Text1", Value = "1" });
obj2.Add(new SelectListItem { Text = "Text2", Value = "2" });
obj2.Add(new SelectListItem { Text = "Text3", Value = "3" });
ViewBag.State1 = obj1;
ViewBag.State2 = obj2;
return View();
}
View
#Html.DropDownList(“State1”)
#Html.DropDownList(“State2”)
but in my opinion better way is using ViewModel for this issue .
I have used the following .net code. Which shows the holiday date which I store in database.
But i want to show some message when I hover the mouse on the date.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connection = #"server=TOPHAN-PC; Database=Tophan;uid=sa;pwd=123";
SqlConnection con = null;
protected DataSet dsHolidays;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con = new SqlConnection(connection);
Calendar1.VisibleDate = DateTime.Today;
FillHolidayDataset();
}
}
protected void FillHolidayDataset()
{
DateTime firstDate = new DateTime(Calendar1.VisibleDate.Year, Calendar1.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
dsHolidays = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (Calendar1.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = Calendar1.VisibleDate.Year + 1;
}
else
{
monthNumber = Calendar1.VisibleDate.Month + 1;
yearNumber = Calendar1.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
DataSet dsMonth = new DataSet();
try
{
//ConnectionStringSettings cs;
//cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
//String connString = cs.ConnectionString;
//SqlConnection dbConnection = new SqlConnection(connString);
String query = "SELECT CDate FROM calender WHERE CDate >= #firstDate AND CDate < #lastDate";
con.Open();
SqlCommand dbCommand = new SqlCommand(query, con);
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("#lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
sqlDataAdapter.Fill(dsMonth);
}
catch
{ }
return dsMonth;
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
FillHolidayDataset();
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
try
{
DateTime nextDate;
if (dsHolidays != null)
{
foreach (DataRow dr in dsHolidays.Tables[0].Rows)
{
nextDate = (DateTime)dr["CDate"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
catch
{ }
}
}
By using this code,I find out that it highlighted the date with the color but I want some message when I move the mouse on the Date.
you can do it by this:
$(document).ready(function()
{
$("#holiday").hover(function () {
//Show whatever message on hover in
},
function () {
//Show whatever message on hover out
}
); });
The following code displays only the last record from the database. How to display all records?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=softmail;" + "UID=root;" + "PASSWORD=********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select name, email, website, comments from awm_comments", MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
while (dr.Read())
{
if (!IsPostBack)
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
ArrayList values = new ArrayList();
values.Add(new PositionData(a, b, c, d));
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
}
}
}
public class PositionData
{
private string name;
private string ticker;
private string val3;
private string val4;
public PositionData(string name, string ticker, string val3, string val4)
{
this.name = name;
this.ticker = ticker;
this.val3 = val3;
this.val4 = val4;
}
public string Name
{
get
{
return name;
}
}
public string Ticker
{
get
{
return ticker;
}
}
public string Val3
{
get
{
return val3;
}
}
public string Val4
{
get
{
return val4;
}
}
}
}
At the moment you are creating a new ArrayList for each record; then, you're binding that new list to the repeater and overwriting the previous binding.
Instead, you need to add all your values to your list and only bind it once you've read all of your data - move your variable declaration before your loop and your DataBind invocation after your loop, like so:
ArrayList values = new ArrayList();
while (dr.Read())
{
if (!IsPostBack)
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
values.Add(new PositionData(a, b, c, d));
}
}
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
You are constantly resetting the values for that repeater.
What you should do is first collect all records into a single ArrayList and only when that is done execute a single DataBind();
Something like:
if (!IsPostBack)
{
ArrayList values = new ArrayList();
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
values.Add(new PositionData(a, b, c, d));
}
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
}