I have a GridView which displays data from MySQL database
When I enter the code to display this information, everything works fine. However, after displaying the information, it continues to form duplicates of the same data.
Ex. The gridview would show the table
Customer ID Username Password
1 root root
2 pie root
3 apple root
1 root root
2 pie root
3 apple root
and ongoing..
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string strConn = "server=localhost;user id=root;password=root;database=database";
string sql = "SELECT entryform.username, entryform.email, entryform.password, entryform2.firstname, entryform2.surname, entryform2.phonenumber, entryform2.ext, entryform2.jobtitle, entryform2.company, entryform2.country, entryform2.provincestate, entryform2.city, entryform2.address1, entryform2.address2, entryform2.zip, entryform.customerid FROM entryform, entryform2";
MySqlConnection conn = new MySqlConnection(strConn);
MySqlDataAdapter dA = new MySqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
conn.Open();
dA.Fill(ds, "entryform,entryform2");
dataGridView.DataSource = ds;
dataGridView.DataBind();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm still fairly new so I am not sure what I did wrong or what else I need to add to fix this error. If anyone can provide any tips, that would be great!
Thanks in advance!
Try this:
dataGridView.Clear();
because maybe you are filling the dataGridView more than once! ;)
If is that you are getting duplicate values from the database, try this:
string sql = "SELECT DISTINCT entryform.username, entryform.email, entryform.password, entryform2.firstname, entryform2.surname, entryform2.phonenumber, entryform2.ext, entryform2.jobtitle, entryform2.company, entryform2.country, entryform2.provincestate, entryform2.city, entryform2.address1, entryform2.address2, entryform2.zip, entryform.customerid FROM entryform, entryform2";
I hope this helps
Related
I have 2 laptops that both have visual studios. I have the exact program on both computers and the Datagridview is only populating on one of them, when its the exact code on both computers. Datagridview is getting populated from SQL Server, which is being hosted on a sever. Both computers have Visual Studio. I am not getting any errors. Not sure if the code is wrong or not, but I'm really trying to understand why it would only be working on 1 computer if its the same code.
I'm trying to populate the datagridview and be able to select a date and it will only show data associated with that date.
This is the code - cargoBoardDate is a datetime picker:
private void GetCargoBoard(string command)
{
var calander = cargoBoardDate.Value.ToShortDateString();
DataTable dt = new DataTable();
SqlDataAdapter da;
connection.Open();
string sql = "SELECT * FROM CargoBoard WHERE DateID LIKE #DateID";
using (var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#DateID", "%" + calander + "%");
connection.Close();
connection.Open();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
da.Dispose();
dgvCargoBoard.DataSource = dt;
connection.Close();
}
connection.Close();
}
private void CargoBoard_Load(object sender, EventArgs e)
{
GetCargoBoard("SELECT * FROM CargoBoard");
HeaderDesign();
hideColumn();
RenameHeader();
formSize();
}
Also my connection string is being called from a class (below):
SqlConnection connection = new SqlConnection(Helper.conString("LoadPlanner"));
I have also tried having the parameter line as such:
cmd.Parameters.AddWithValue("#DateID", calander);
If someone could explain to me what is going on for it to work on 1 machine but not another with the exact code and a possible solution?
Thank you!
May be a noob question. But I am scratching my head what I am doing wrong here.
protected void ddlClientNum_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Bussiness.GetConnectionString("Default")))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select distinct client_name from [dbo].[customer_master] where client_number=" + ddlClientNum.SelectedItem.Text + " order by client_name", con);
adapter.Fill(dt);
ddlClientName.DataSource = dt;
ddlClientName.DataTextField = "client_name";
ddlClientName.DataValueField = "client_name";
ddlClientName.DataBind();
ddlClientName.ClearSelection();
//ddlClientName.SelectedValue = ddlClientName.Items.FindByText((ddlClientNum.SelectedItem.Text).ToString()).Value;
//ddlClientName.SelectedValue = ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()).Value;
//ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()).Selected = true;
ddlClientName.SelectedIndex = ddlClientName.Items.IndexOf(ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()));
}
}
}
I am populating client number and client name dropdownlist on page load. On selection of client number I need to select the respective client name but I don't want to Clear the Items. I need users to be able to see the other client names but need to Select the Client name for selected client Number. I Have tried the 3 things but it keeps adding the selected client name.
So, selected client name is occurring as many times I select the respective Client Number and stays there even if I select another client Number.
e.g. I select Client Number :176 | Client Name shows "XYZ Client" selected but occurs twice in the list. If I select any other client number and then again select 176 I can see "XYZ Client" occuring in the list thrice.
Blues and yellows are the repeating ones.
Then you don't need to bind again here. just set the selected index.
Also, I suggest you to use Parameterized queries. Otherwise, It will be vulnerable to SQL injection.
For more info : https://www.mssqltips.com/sqlservertip/2981/using-parameters-for-sql-server-queries-and-stored-procedures/
protected void ddlClientNum_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Bussiness.GetConnectionString("Default")))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select distinct client_name from [dbo].[customer_master] where client_number=" + ddlClientNum.SelectedItem.Text + " order by client_name", con);
adapter.Fill(dt);
ddlClientName.ClearSelection();
ddlClientName.SelectedIndex = ddlClientName.Items.IndexOf(ddlClientName.Items.FindByText((dt.Rows[0][0]).ToString()));
}
}
}
I have 2 form in my application Form1 and summary. I have a button in form1 onclick I will choose a mdb file then it gets connected to mdb. I have a datagridview in summary.
What I need is once I connect the mdb file I need to update the data (in other words set datagrid.DataSource = ds from Form1) so that the data from mdb shows on datagridview of summary Form
Before selecting my question as duplicate or -1 plzz make clear that database will be connected in form1 which needs to be show in summary form. I had tried all the ways shown in google but no result.
Your help will be appreciated.
got it make another constructor in summary form that have paramater like that
public summary(dataset ds){
initializecomponent();// there
// here bind the DataSet with grid of summary
}
call from form1
summary obj = new summary (ds);
obj.show();
I think you're talking about changing the connection string, like:
private SqlConnection getConn(string Initial_Catalog_Name_Of_Database)
{
return new SqlConnection(#"Data Source=DESKTOP-JHHHN0A\MLSQLSRVR16;Initial Catalog="+Initial_Catalog_Name_Of_Database+";Integrated Security=True;Connection Timeout=9600");
}
Then
private void non_Query(string sql)
{
using (SqlConnection conn = getConn())
{
conn.Open();
using (SqlCommand com = conn.CreateCommand())
{
com.CommandTimeout = 900;
com.CommandText = sql;
com.ExecuteNonQuery();
}
conn.Close();
}
}
If that's not your question, please post your code and be more specific about what you need.
On the Summary Form Load, Query DB and populate your DataGridView.
Use the below sample code on your Form Load.
string connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your .mdb file;";
string sql = "SELECT * FROM Authors";
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
I've been squeezing my mind trying to figure out why my code isn't working.
I am trying to read from a DataSet that filled with data from access database and insert the data into an Oracle database which is created previously.
When I try the following code it won't work and although I use the try and catch block, when debugging it would freeze and won't show me any error.
if can see that I have commented out the block just right above my foreach loop..which works perfectly, Any help from you is so much appreciated :
private void button3_Click(object sender, EventArgs e)
{
string query1 = "Select * from Test;";
string StrQuery= "Insert Into TEST (ID, DATA) Values (:ID, :DATA)";
Conn = new OleDbConnection(connStr);
Conn.Open();
using (OleDbConnection connection1 = new OleDbConnection(connStr))
{
using (OleDbDataAdapter adapter1 = new OleDbDataAdapter(query1, connection1))
{
DataSet ds1 = new DataSet();
adapter1.Fill(ds1);
// no need for refilling DataGridView1.DataSource = ds.Tables[0]
// insterting the dataset into oracle
try
{
using (OracleConnection connect = new OracleConnection(oradb1))
{
connect.Open();
using (OracleCommand comma = new OracleCommand(StrQuery, connect))
{
/*comma.Parameters.Add(new OracleParameter(":ID", 2));
comma.Parameters.Add(new OracleParameter(":DATA", 2));
comma.ExecuteNonQuery();*/
foreach (DataRow drRow in ds1.Tables[0].Rows)
{
for (int i = 0; i < ds1.Tables[0].Columns.Count; i++)
{
comma.Parameters.Add(new OracleParameter(":ID", drRow[i]));
comma.Parameters.Add(new OracleParameter(":DATA", drRow[i]));
comma.ExecuteNonQuery();
}
}
connect.Close();
connect.Dispose();
}
}
}
catch (OracleException)
{
System.Diagnostics.Debugger.Break();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Conn.Close();
}
You are looping columns but adding the drRow[i] as values in the parameters.
I do not think this is what you intended.
skip the columns loop and add the first column value to id and second column value to data.
that should be what you wanted.... if not then describe a bit more...
Expanding on Judgemaik's answer, I believe you need to do something like this instead (can't really tell what the names of the columns in your access table are but you get the idea:
foreach (DataRow drRow in ds1.Tables[0].Rows)
{
comma.Parameters.Add(new OracleParameter(":ID", drRow["IDColumnFromAccessDB"]));
comma.Parameters.Add(new OracleParameter(":DATA", drRow["DATAColumnFromAccessDB"]));
comma.ExecuteNonQuery();
}
A similar approach is outlined in my answer here. In that particular case I was moving data from SQL Server Compact into Access, but the same idea could very well be used to move data between any two OleDb data sources.
It uses an OleDbDataAdapter to pull the source table into a DataTable, copies it over to another DataTable, and then uses another OleDbDataAdapter to update the corresponding table in the destination database.
guys here is what i have come up with I cant figure out what is the prob that is not allowing me to update the tables in the database
guys I need ur help I need to update my data base through data grid using c# as of yet all that I am able to do is that I am able to see the values that are inside the sql server that I put directly.`
string sConnectionString = "Data Source=localhost;Initial Catalog=ScratchCardSystem2;Integrated Security=True;pooling=true";
SqlConnection objConn = new SqlConnection(sConnectionString);
objConn.Open();
string query = "SELECT * FROM store_adj_note_detail_1";
SqlDataAdapter dAdapter = new SqlDataAdapter(query,objConn);
//dAdapter.SelectCommand= new SqlCommand(query, objConn);
SqlCommandBuilder cBuilder = new SqlCommandBuilder(dAdapter);
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
dataGridView1.DataSource = dTable;
dAdapter.Update(dTable);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dAdapter);
Is missing.
MSDN says:
//Without the OleDbCommandBuilder this line would fail.
dAdapter.Update(dTable);
You are missing something that binds your datagridview to your datatable. The trick here is that you need a BindingSource.
Add the following before your '//fille the datatble' line
BindingSource bindSrc = new BindingSource();
Then change your datasource of your datagridview and add a source to your bindingsource as well, like this:
dataGridView1.DataSource = bindSrc;
bindSrc.DataSource = dTable;
EDIT: I forgot to mention a tiny thing: to update, you now have to refer to the datatable that is the source of your bindingSrouce, this is how I did it:
dAdapter.Update((DataTable)bindSrc.DataSource);
Might be possible just with the regular update(dTable), but if it doesn't, this probably fixes it
So this is basically what I used for my own form. On establish connection the connection opens and it fills up my datagridview1 with the data from store_adj_note_detail_1.
Notice I never declare my bindingSource... I don't know the reason either, but I tried declaring it with the rest of them (globally) and locally, both made the code break :/
The declaration of your BindingSource happens on the Design view of your form - just drag it from the toolbox on top of your form and it will show up with an icon like FileDialogs and Menustrips do. I personally only changed the Name property and didn't add any events.
It should give you the overview of everything you need to open a connection, use the bindingsource to link your datagridview and your dataTable, and update your database.
I got this code by editing my own code that I used for an access database, but SQL databases seem to work exactly the same way, just with different entities (sqlDataAdapter and the likes instead of OleDb...).
hope this helps you!
public partial class FrmDatabaseConnection : Form
{
// Connection, Adapter, DataTable, CommandBuilder, Bindingsource and command
private SqlDataAdapter adap;
private DataTable dataTable;
private SqlCommandBuilder commandBuilder;
private string sqlCommand = "SELECT * FROM store_adj_note_detail_1";
private SqlConnection conDB = new SqlConnection();
//To open connection and fill datagridview1
private void establishConnection()
{
try
{
conDB.ConnectionString = "Data Source=localhost;Initial Catalog=ScratchCardSystem2;Integrated Security=True;pooling=true";
conDB.Open();
// Set adapter, commandbuilder, datatable and bindingsource
adap = new SqlDataAdapter(sqlCommand, conDB.ConnectionString);
commandBuilder = new SqlCommandBuilder(adap);
bindSrc = new BindingSource();
dataTable = new DataTable();
// Fill it!
adap.Fill(dataTable);
dataGridView1.DataSource = bindSrc;
bindSrc.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show("Unable to Open database, " + ex.Message,);
conDB.Close();
}
}
private bool saveToDatabase()
{
try
{
adap.Update((DataTable)bindSrc.DataSource);
}
catch (Exception ex)
{
MessageBox.Show("Unable to Update database, " + ex.Message);
return false;
}
}
}