So here I'm trying to populate my dropdown list, the code behind is as below:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
con.Open();
SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
SqlDataReader ddlvalues = mycommand.ExecuteReader();
ddlTransactionCategory.DataSource = ddlvalues;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
mycommand.Connection.Close();
mycommand.Connection.Dispose();
}
the problem is, I can't seem to get it to work, any help? and is this code doing it right?
plz try below code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
con.Open();
SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
SqlDataAdapter adp =new SqlDataAdapter(mycommand);
DataSet ds =new DataSet();
adp.Fill(ds);
ddlTransactionCategory.DataSource = ds;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
mycommand.Connection.Close();
mycommand.Connection.Dispose();
}
Thanks,
Hitesh
Can't bind to a SqlDataReader (or at least I've never tried it). Get a DataTable or a DataSet instead, fill it and then bind that to the dropdown the same way.
Use SqlDataAdataper like the one below
using (SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from MSUnit", con);
DataTable dt = new DataTable
da.Fill(dt)
ddlTransactionCategory.DataSource = dt;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
}
if you want to use DataReader you must insert one-by-one.
while (ddlvalues.Read())
{
ddlTransactionCategory.Items.Add(new ListItem(ddlvalues.getString("OrgID"),ddlvalues.getString("categoryCode")))
}
Related
I am getting an error:
cannot convert from MySql.Data.MysqlClient.MySqlCommand to
'System.Data.SqlClient.SqlCommand' at SqlDataAdapter sda = new SqlDataAdapter(cmd);
string MyConnectionString = "Server=localhost;Database=smsjobs;Uid=root;pwd=root;";
protected void Submit_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd; connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText="select * from userdetails where db_mobi=#username and db_pass=#word";
cmd.Parameters.AddWithValue("#username", cn_mobi.Text);
cmd.Parameters.AddWithValue("#word", cn_pass.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);// getting error here
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
connection.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = cn_mobi.Text;
Response.Redirect("Redirectform.aspx");
Session.RemoveAll();
}
}
You're trying to make SqlDataAdapter (the one for MS SQL) working with MySqlCommand. There is a MySqlDataAdapter, so looks like you need to be using it instead.
But anyway, this code makes no sense:
SqlDataAdapter sda = new SqlDataAdapter(cmd);// getting error here
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
You're calling DataAdapter to fill DataTable via SqlCommand, and then call that SqlCommand again with ExecuteNonQuery. That`s totally nonsense.
You need to change your code to this (probably):
string MyConnectionString = "Server=localhost;Database=smsjobs;Uid=root;pwd=root;";
protected void Submit_Click(object sender, EventArgs e) {
using(var connection = new MySqlConnection(MyConnectionString)) {
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText="select * from userdetails where db_mobi=#username and db_pass=#word";
cmd.Parameters.AddWithValue("#username", cn_mobi.Text);
cmd.Parameters.AddWithValue("#word", cn_pass.Text);
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Session["id"] = cn_mobi.Text;
Response.Redirect("Redirectform.aspx");
Session.RemoveAll();
}
}
}
Note the using instead of direct connection.Close()
I think you should use System.Data.OleDb;namespace and in that namespace you have same classes. Means instead of SqlConnection you should use OleDbConnection and in place of SqlDataAdapter you can use OleDbDataAdapter.
I think it should work. Hope this will help.
I think you should change
SqlDataAdapter sda = new SqlDataAdapter(cmd);
to
MySqlDataAdapter sda = new MySqlDataAdapter (cmd);
Since SqlDataAdapter is not going to be overloaded with MySqlCommand.
I am trying to change value of a TextBox control after the value of ComboBox changes. My code returns System.Data.DataRowView on the first time ComboBox value changes.
That is why I am getting an Object instead of the actual value on first call to my combobox.
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionString"].ConnectionString);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd= new SqlCommand("SELECT donor_name,ID FROM donor_detail",con);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
DonorName.DataSource = dt;
DonorName.DisplayMember = "donor_name";
DonorName.ValueMember = "ID";
con.Close();
}
And this is Event of change Value of ComboBox which is supposed to change value of my TextBox also when value in ComboBox changes.
private void DonorName_SelectionChangeCommitted(object sender, EventArgs e)
{
var id = Convert.ToString(DonorName.SelectedValue);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionString"].ConnectionString);
con.Open();
String sql = "SELECT * from donor_detail WHERE ID=" + id + "";
SqlCommand cmd = new SqlCommand(sql,con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
MessageBox.Show(sql);
mobile.Text = dt.Rows[0]["mobile"].ToString();
con.Close();
}
As mentioned here and several other places, this happens if you don't specify the datasource after the display and value members. This is the correct order:
DonorName.DisplayMember = "donor_name";
DonorName.ValueMember = "ID";
DonorName.DataSource = dt;
I have to display chart that is connected with db dynamically. It is working fine. The code is given below. But my issue is my db is automatically update in every 5 minutes. So I have to display the chart with latest inserted information. Please help me.
The code is given below:
public partial class chartDummy : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(#"ConnectionString");
cmd = new SqlCommand("Select Mains_Run_Hrs, DG_Run_Auto_Mode, Battery_Run_Hrs, Solar_Run_hrs from tbl_runtime_report", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataView source = new DataView(ds.Tables[0]);
Chart1.DataSource = ds;
Chart1.Series[0].YValueMembers = "Mains_Run_Hrs";
Chart1.Series[0].XValueMember = "DG_Run_Auto_Mode";
Chart1.Series[0].XValueMember = "Battery_Run_Hrs";
Chart1.Series[0].XValueMember = "Solar_Run_hrs";
Chart1.DataBind();
}
}
cmd = new SqlCommand("Select Mains_Run_Hrs, DG_Run_Auto_Mode, Battery_Run_Hrs, Solar_Run_hrs from tbl_runtime_report ORDER BY Site_ID DESC", con);
I'm new to c#, as in.
I'm currently working on a search function in c# using 3 DropDownLists and a submit button. When a user select an item on DropDownList and click submit, it will print the table for the respective selection.
There are 3 DropDownLists:
a province,
city,
specialization.
This will search the available doctors that suits the selection. For example I choose province1 on 1st DropDownList, city1 on the 2nd and a psychologist on 3rd, when the submit button is fired, it will print the available doctors that is in province1, city1 and has a specialization of psychologist.
I already have a code, still figuring it out but, when i click the submit button, nothing is happening. Can someone help me?
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
ddlProvince.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_specialization", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPEC_NAME";
ddlSpec.DataValueField = "SPEC_CODE";
ddlSpec.DataBind();
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void btnSub_Click(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_doctors");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where Province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
}
}
Make change in this line of code which is in submit button click function
Correct code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
because as you see your code query is incorrent have look to your code which is incorrect
Wrong code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where (" + ddlProvince.SelectedItem.ToString() + " ", conn);
Edit:
if you want to display record that you got in DataTable you either need loop through the records or you need to use GridView for that...i think you miss that thing
in above one after where clause you miss the name of the filed you need to made filter on... i have written update code by modifying that condition.
See MSDN for GridView.
You said that after clicking submit, nothing happend. But in btnSub_Click I didn't see anything that displaying the result or changing anything on the page. You should bind dt to some control like a gridview etc.
I am creating a inventory app using c# that pulls its info from sql server. I am making it a tabbed view, with each tab representing a different type of item. I have included some of my code, what I am trying to figure is, is there a better way to do this? I dont feel like the way I am doing is right, even though it works. All my queries for each tab are stored procedures. Secondly, How would I insert and update the database through the grid?
public partial class InventoryWindow : Window
{
private InventoryDS InvDS;
private String connString = "server=PC-server;database=Inventory;user=user;password=password";
String sqlString_Routers = InventoryOutputQuery.InventorySummary_Routers();
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter(sqlString_Routers, con);
DataSet ds = new DataSet();
adpt.Fill(ds, sqlString_Routers);
dgDataView.DataContext = ds;
}
}
private void showTaps()
{
String sqlString_Taps = InventoryOutputQuery.InventorySummary_Routers();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Routers, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
private void showPower()
{
String sqlString_Power = InventoryOutputQuery.InventorySummary_Power();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Power, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
private void showSwitches()
{
String sqlString_Switches = InventoryOutputQuery.InventorySummary_Switches();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Switches, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
And below is how i bind it to the grid:
public void BindGrid(string view)
{
switch (view.ToUpper())
{
case "Routers":
showTaps();
break;
case "POWER":
showPower();
break;
case "SWITCHES":
showSwitches();
break;
case "HUBS":
showHubs();
private void tcDataView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabItem ti = tcDataView.SelectedItem as TabItem;
if (ti != null)
BindGrid(ti.Header.ToString());
}
break;
My suggestion is to be careful with how we handle SqlConnection. It is a scarce resource and it will run out pretty soon if we are not careful.
Please wrap sql code in a using block, for example:
using (SqlConnection con = new SqlConnection(connString))
{
SqlDataAdapter adpt = new SqlDataAdapter(sqlString_Routers, con);
DataSet ds = new DataSet();
adpt.Fill(ds, sqlString_Routers);
dgDataView.DataContext = ds;
}
The following link will explain the effect of 'using' block in a bit more details.
http://www.codeproject.com/KB/cs/tinguusingstatement.aspx