I have an asp.net web site I'm trying to develop and I have an issue loading data from a database. It worked fine in a C# WebForm App and I was wondering what i need to do to get it to work correctly in the asp.net project and bind the results to a dropdownlist to be selected from.
try
{
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "127.0.0.1",
InitialCatalog = "PIIMSDATA",
IntegratedSecurity = true
};
SqlConnection cs = new SqlConnection(connectionStringBuilder.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Book1 Order by ID", cs);
}
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
//DropDownList2.DataSource = ds.Tables[0];
//DropDownList2.DataTextField = "ID";
//DropDownList2.DataValueField = "ID";
//DropDownList2.DataBind();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true);
//MessageBox.Show(ex.Message);
}
}
There are many ways to do that. Here's an example that I've ever tried:
public string connectionString = "Data Source = YOUCANSEEONSQLSERVER; Initial Catalog = DATABASENAME; User Id = sa; Password = sqlpasswordifyouuse";
private void Valetin_Load(object sender, EventArgs e)
{
OPIDCB.ResetText();
ValetCB.ResetText();
SqlConnection sqlconn = new SqlConnection(pr.connectionString);
SqlCommand sqlselect1 = new SqlCommand("Select EmpID, EmpName from Employees.Employee where IDPosition = 'OP'", sqlconn);
sqlconn.Open();
SqlDataReader dr1 = sqlselect1.ExecuteReader();
while (dr1.Read())
{
ArrayList MyAL = new ArrayList();
ArrayList MyAL2 = new ArrayList();
MyAL.Add(dr1.GetString(0));
MyAL2.Add(dr1.GetString(1));
foreach (string s in MyAL)
foreach (string s2 in MyAL2)
{
OPIDCB.Items.Add(s + " " + s2);
}
OPIDCB.SelectedIndex = 0;
}
dr1.Close();
sqlconn.Close();
}
If you are confusing with that code, you can visit this link: What is the right way to populate a DropDownList from a database?
Hope this help.
You can create connection string in web.config and get this param to bind in dropdownlist
Try to this link :
http://www.c-sharpcorner.com/UploadFile/rohatash/binding-dropdownlist-with-database-and-display-data-in-gridv/
Related
I am having trouble with my SQL statement to pass the value from my dropdownlist select to my gridview. I tested my SQL statement Serve Management Studio, with a specific date, and it works, but it isn't working with select value from my Dropdownlist. How would I pass the value to the Gridview? Thank you for help, I am new student to the asp.net world.
Image of web application:
Image of My DATABASE:
public void RefreshDay()
{
SqlConnection conn = new SqlConnection(#"data source =.\sqlexpress; integrated security = true; database = DBdentist");
SqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
string sqlsel = "SELECT Distinct patient.patientID, day from patient, patientreservation where patient.patientID = patientreservation.patientID";
try
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sqlsel, conn);
ds = new DataSet();
da.Fill(ds, "myDay");
dt = ds.Tables["myDay"];
DropDownListDay.DataSource = dt;
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "patientID";
DropDownListDay.DataBind();
DropDownListDay.Items.Insert(0, "Select Day");
}
catch (Exception ex)
{
LabelDay.Text = ex.Message;
}
finally
{
conn.Close();
}
}
protected void DropDownListDay_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownListDay.SelectedIndex != 0)
{
SqlConnection conn = new SqlConnection(#"data source =.\sqlexpress; integrated security = true; database = DbDentist");
SqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
string sqlsel = "SELECT patientreservation.patientID, patient.firstname, patient.lastname, patientreservation.day, patientreservation.hour, treatment.treatment FROM((patientreservation INNER JOIN patient ON patientreservation.patientID = patient.patientID) INNER JOIN treatment ON patientreservation.treatmentID = treatment.treatmentID) WHERE patientreservation.day = " + DropDownListDay.SelectedValue + "";
try
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sqlsel, conn);
ds = new DataSet();
da.Fill(ds, "myDay");
dt = ds.Tables["myDay"];
GridViewDay.DataSource = dt;
GridViewDay.DataBind();
}
catch (Exception ex)
{
LabelDay.Text = ex.Message;
}
finally
{
conn.Close();
}
}
else
{
LabelDay.Text = "You choose None:";
}
}
}
}
You can simply use this:
WHERE patientreservation.day = '" + DropDownListDay.Text.ToString() + "'";
Thanks for the help. I tried everything
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "day"
helped. I was also having some problem with my gridview. I added up deleting it and making a new, somehow that help.
The configuration of your dropdown is
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "patientID";
but you need the day as a value if you want to filter with the current selected value
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "day";
SELECT patientreservation.patientID, patient.firstname, patient.lastname, patientreservation.day, patientreservation.hour, treatment.treatment FROM((patientreservation INNER JOIN patient ON patientreservation.patientID = patient.patientID) INNER JOIN treatment ON patientreservation.treatmentID = treatment.treatmentID) WHERE **patientreservation.day** = " + DropDownListDay.**SelectedValue** + "";
Or you can try with WHERE **patientreservation.day** = " + DropDownListDay.**SelectedText** + "";
The dropdownlist is not triggering the event. Try to put this AutoPostBack="true" in your asp dropdownlist tag.
m developing application for my office and in my application there is a datagrid view that linked to a mysql database. local users can update the database using datagridview but they cant delete any recodes. i want to implement a method that user's are select exact raw in the datagridview and delete it as well as delete the database record soon. i managed to make select and delete datagridview row using below code but it not update the database
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
and this is my connection string that i normally use to view the database data in datagrid view. i don't have good knowledge to combined these two.can someone please show me how to do that
my connection string
private void showdatagrid()
{
string constring = string.Format("datasource='{0}';username=******;port=3306;password=***********;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from warit.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try this code
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
int loannumber = dataGridView1.Rows[oneCell.RowIndex].Cells['index of loannumber column in datagridview'].Value; // assuming loannmber is integer
string username = dataGridView1.Rows[oneCell.RowIndex].Cells['index of username column in datagridview'].Value; // assuming username is string
/* Now create an object of MySqlConnection and MySqlCommand
* and the execute following query
*/
string query = string.Format("DELETE FROM table_name WHERE loannumber = {0} AND username = '{1}'", loannumber, username);
}
}
}
string connection = "server = URL; uid = user; pwd = password; database = database;";
using (MySqlConnection conn = new MySqlConnection(connection)) {
conn.Open();
string idLocRemv = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string removeVolCred = "DELETE FROM TableName WHERE ID = " + idLocRemv;
using (MySqlCommand command = new MySqlCommand(removeVolCred, fbcConn)) {
command.ExecuteNonQuery();
}
conn.Close();
}
Apply necessary exception handlers. (try catch finally)
Additionally, you will need to re-load DataGridView afterwards.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can WCF consuming data from database phpmyadmin?
I want to ask about the connection string that should i write at WCF. My database is host at phpmyadmin.
How should I write the connections string? if the database is using microsoft access or sqlserver that run at my computer, I done it already. Now, I'm curious if my database at phpmyadmin.
Honestly, I already asked this question in this forum yesterday. I say a big thanks to whom answer my question but I dont think that is a answer. I'm sorry for being stupid and don't understand what you said yesterday. If you get mad, you don't need to answer. thanks.
Out of the topic, this my WCF code.
public class Jobs : IJobs
{
SqlConnection conn = new SqlConnection("Data Source=127.0.0.1; Initial Catalog=mydatabase;User=ael;Password=123456;Integrated Security=False");
SqlDataAdapter da;
DataSet ds;
Data data = new Data();
List<Data> listdata = new List<Data>();
public DataSet Details()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
conn.Close();
return ds;
}
public Data GetDetails(int jobid)
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data where id = " + jobid, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
data.userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
data.firstname = ds.Tables[0].Rows[0][1].ToString();
data.lastname = ds.Tables[0].Rows[0][2].ToString();
data.location = ds.Tables[0].Rows[0][3].ToString();
ds.Dispose();
}
conn.Close();
return data;
}
public List<Data> GetAllDetails()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
listdata.Add(
new Data
{
userid = Convert.ToInt32(dr[0]),
firstname = dr[1].ToString(),
lastname = dr[2].ToString(),
location = dr[3].ToString()
}
);
}
conn.Close();
return listdata;
}
}
this is the wpf
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textbox1.Text.Trim().Length != 0)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
var x = jc.GetDetails(Convert.ToInt32(textbox1.Text));
if (x.userid != 0)
{
textbox2.Text = x.userid.ToString();
textbox3.Text = x.firstname;
textbox4.Text = x.lastname;
textbox5.Text = x.location;
}
else
MessageBox.Show("RecordNotFound ... !", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
MessageBox.Show("EnterID", "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.Details().Tables[0].DefaultView;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.GetAllDetails() ;
}
}
I already create a user at phpmyadmin, and use it at my WCF. but whenever I run, its show "login failed for user ael".
Is there something I need to change in the connection string?
thanks before.
If I understand correctly you need an example for the connection string.
So for the connection string format please see ConnectionsStrings.com
For example, if you are using the standard port and did not change it:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Then you can to use the MySQL Connector (Namespace MySql.Data.MySqlClient downloadable here) and connect to the MySQL database programatically as explained in detail in this tutorial: Connection to the MySQL Server.
nice to meet you all. I'm new in here.
Just want to ask, how can my WCF consume data from database phpmyadmin?
I just tried my WCF consume data from database sqlserver and it works in my wpf app.
But I can't find a way how can my WCF access the data if my database is online.
is there any clue?
i try to change the data source into the IP at my database, it doesn't work.
here is my SqlConnection,
SqlConnection conn = new SqlConnection("Data Source=Alfred-PC;Initial Catalog=alfred;Integrated Security=True");
This is the WCF
public class Jobs : IJobs
{
SqlConnection conn = new SqlConnection("Data Source=Alfred-PC;Initial Catalog=alfred;Integrated Security=True");
SqlDataAdapter da;
DataSet ds;
Data data = new Data();
List<Data> listdata = new List<Data>();
public DataSet Details()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
conn.Close();
return ds;
}
public Data GetDetails(int jobid)
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data where id = " + jobid, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
data.userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
data.firstname = ds.Tables[0].Rows[0][1].ToString();
data.lastname = ds.Tables[0].Rows[0][2].ToString();
data.location = ds.Tables[0].Rows[0][3].ToString();
ds.Dispose();
}
conn.Close();
return data;
}
public List<Data> GetAllDetails()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
listdata.Add(
new Data
{
userid = Convert.ToInt32(dr[0]),
firstname = dr[1].ToString(),
lastname = dr[2].ToString(),
location = dr[3].ToString()
}
);
}
conn.Close();
return listdata;
}
}
this is the WPF file
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textbox1.Text.Trim().Length != 0)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
var x = jc.GetDetails(Convert.ToInt32(textbox1.Text));
if (x.userid != 0)
{
textbox2.Text = x.userid.ToString();
textbox3.Text = x.firstname;
textbox4.Text = x.lastname;
textbox5.Text = x.location;
}
else
MessageBox.Show("RecordNotFound ... !", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
MessageBox.Show("EnterID", "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.Details().Tables[0].DefaultView;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.GetAllDetails() ;
}
}
If I understand correctly you need an example for the connection string.
So for the connection string format please look here: http://www.connectionstrings.com/mysql
An example could be Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword; if you are using the standard port and did not change it. In this case you won't use integrated security though (you will specify the username and password in the connection string) so check if that is possible for you.
Then you may use the MySQL Connector (Namespace MySql.Data.MySqlClient downloadable here http://dev.mysql.com/downloads/dotnet.html) and connect to the MySQL database programatically as explained in detail here http://www.functionx.com/mysqlnet/csharp/Lesson02.htm
You're using integrated security. In the case of the WPF app, so the account used to authenticate access to the DB is the account you're logged in as. But in the WCF service, the account is controlled by the settings for the (IIS) server hosting it. You have some options:
Change to use a username and password to connect to the DB
Change the DB to accept the account that the WCF service is trying to connect as (the DB should tell you in an error message or log)
Change the server settings to use a Windows account that has privileges
I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.