i am working on windows from application..i am filling my data grid view like this:
Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter = New SqlDataAdapter("select c.cid,c.CompanyName,l.LocName as Location,d.dtId,d.dtName as Department,d.dtPhone as Phone,d.dtEmail as Email,l.Locid from CompanyMaster_tbl c join DepartmentMaster_tbl d on c.Cid=d.cId join Location_tbl l on l.Locid=c.locid where d.Deleted =0 and c.Deleted=0 order by cid", con.connect)
dt1 = New DataTable
bSource = New BindingSource
adapter.Fill(dt1) 'Filling dt with the information from the DB
bSource.DataSource = dt1
gv.DataSource = bSource
gv.Columns("cid").Visible = False
gv.Columns("dtId").Visible = False
gv.Columns("Locid").Visible = False
in update button I have code like this:
adapter = New SqlDataAdapter()
Dim cid As Integer
Dim dtid As Integer
Dim cmpname As String
Dim dtname As String
Dim dtPhone As String
Dim dtEmail As String
Dim LocName As String
Dim Locid As Integer
For i As Integer = 0 To gv.RowCount - 2
Dim rv = DirectCast(gv.Rows(i).DataBoundItem, DataRowView)
cid = rv.Row.Field(Of Integer)("Cid")
dtid = rv.Row.Field(Of Integer)("dtId")
cmpname = rv.Row.Field(Of String)("CompanyName")
LocName = rv.Row.Field(Of String)("Location")
dtname = rv.Row.Field(Of String)("Department")
dtPhone = rv.Row.Field(Of String)("Phone")
dtEmail = rv.Row.Field(Of String)("Email")
Locid = rv.Row.Field(Of Integer)("Locid")
adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = #CompanyName", con.connect)
adapter.UpdateCommand = New SqlCommand("Update Location_tbl Set LocName=#LocName where Locid=#Locid ", con.connect)
adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = #dtName,dtPhone = #dtPhone,dtEmail = #dtEmail where dtId=#dtid", con.connect)
adapter.UpdateCommand.Parameters.AddWithValue("#Cid", cid)
adapter.UpdateCommand.Parameters.AddWithValue("#CompanyName", cmpname)
adapter.UpdateCommand.Parameters.AddWithValue("#LocName", LocName)
adapter.UpdateCommand.Parameters.AddWithValue("#dtId", dtid)
adapter.UpdateCommand.Parameters.AddWithValue("#dtName", dtname)
adapter.UpdateCommand.Parameters.AddWithValue("#dtPhone", dtPhone)
adapter.UpdateCommand.Parameters.AddWithValue("#dtEmail", dtEmail)
adapter.UpdateCommand.Parameters.AddWithValue("#Locid", Locid)
adapter.UpdateCommand.ExecuteNonQuery()
Next
while clicking update button I am not getting any error..i can able to update my DepartmentMaster_tbl..but that is not updating my Location_tbl..what is wrong with my code..
any help is very appreciable..thanks
because you are overwriting your UpdateCommands then doing ExecuteNonQuery which will use the current UpdateCommand available (the last one in this case)
to me it looks like you are overwriting the UpdateCommand twice after setting it.
you set it with UPDATE CompanyMaster_tbl then overwrite it with UPDATE Location_tbl and then overwrite it again with update DepartmentMaster_tbl,
as expected only the last one is executed.
a solution using SqlCommand instead of SqlAdapter:
using (SqlConnection DBConn = new SqlConnection("connection string")
{
DBConn.Open();
using (SqlTransaction DBTran = DBConn.BeginTransaction)
{
using (SqlCommand DBCmd = new SqlCommand("your first statement here", DBConn))
{
DBCmd.Transaction = DBTran;
// set only the parameters needed for this table
...
// execute statement
DBCmd.ExecuteNonQuery();
}
// repeat the above block for the other tables
...
// commit transaction to database
DBTran.Commit();
}
}
Related
I am a .Net developer and I am searching for a question that how can I filter combobox values bound from a SQL Server 2012 database.
I have four comboboxes as seen in the Registration Form. I want to filter the values of all these comboboxes as if I select the value in first combobox that value should not be displayed in the other comboboxes.
I am using Visual Studio 2013.
Here is the code for first combobox of Course Name Field:
public void BindData()
{
objcon.Open();
string cmd = "select Course_Name from CourseDetails";
objcom = new SqlCommand(cmd, objcon);
objDA = new SqlDataAdapter(cmd, objcon);
objDS = new DataSet();
objDA.Fill(objDS);
objcom.ExecuteNonQuery();
objcon.Close();
CmBx_Course_Name1.DisplayMember = "Course_Name";
CmBx_Course_Name1.ValueMember = "Course_Name";
CmBx_Course_Name1.DataSource = objDS.Tables[0];
CmBx_Course_Name1.Enabled = true;
}
Here is the code for first combobox of Batch Name Field:
public void BindBatchName()
{
objcon.Open();
string cmd = "select Batch_Name from batch where Batch_Status IS NULL";
objcom = new SqlCommand(cmd, objcon);
objDA = new SqlDataAdapter(cmd, objcon);
objDS = new DataSet();
objDA.Fill(objDS);
objcom.ExecuteNonQuery();
objcon.Close();
CmBx_batch_name1.DisplayMember = "Batch_Name";
CmBx_batch_name1.ValueMember = "Batch_Name";
CmBx_batch_name1.DataSource = objDS.Tables[0];
CmBx_batch_name1.Enabled = true;
}
I am trying to to show on a grid values from database based on selection on a combobox.
OdbcConnection conexiune;
OdbcCommand comanda;
DataSet dsDate;
OdbcDataReader cititor;
DataTable tblClienti;
//conexiune
conexiune = new OdbcConnection();
//string
conexiune.ConnectionString = "Driver={PostgreSQL Unicode};database=postgres;server=localhost;port=5432;uid=postgres;pwd=cpmsur2ms1;sslmode=disable;readonly=0;protocol=7.4;fakeoidindex=0;showoidcolumn=0;rowversioning=0;showsystemtables=0;fetch=100;unknownsizes=0;maxvarcharsize=255;maxlongvarcharsize=8190;debug=0;commlog=0;usedeclarefetch=0;textaslongvarchar=1;unknownsaslongvarchar=0;boolsaschar=1;parse=0;extrasystableprefixes=dd_;lfconversion=1;updatablecursors=1;trueisminus1=0;bi=0;byteaaslongvarbinary=0;useserversideprepare=1;lowercaseidentifier=0;gssauthusegss=0;xaopt=1";
// deschide
conexiune.Open();
// interogam tabela
comanda = new OdbcCommand();
comanda.CommandText = "SELECT * FROM comanda WHERE idclient =?";
comanda.Connection = conexiune;
//parametru
string pidClient;
pidClient = cboClienti.SelectedValue.ToString();
comanda.Parameters.Clear();
comanda.Parameters.AddWithValue("#idclient", pidClient);
Console.WriteLine(pidClient);
//citeste
cititor = comanda.ExecuteReader();
//tabela
tblClienti = new DataTable("COMAND");
tblClienti.Load(cititor);
dsDate = new DataSet();
dsDate.Tables.Add(tblClienti);
//grind
grdComanda.DataSource = dsDate;
grdComanda.DataMember = "COMAND";
grdComanda.Refresh();
conexiune.Close();
idclient is integer type in database.
when i do console.writeline (pidClient) it gives me this :System.Data.DataRowView.
I got this error! When open crystal report upon follong code.
The data source object is invalid.
Code is here
Cursor = Cursors.WaitCursor;
timer1.Enabled = true;
CrystalReport2 rpt = new CrystalReport2();
obj.connection();
String accept = "SELECT S.Product as Products, COALESCE(Pur_Orders.Quantity, 0) as [Products purchased], COALESCE(Sale_Orders.Quantity, 0) as [Products Sold] From Inv_stock S LEFT JOIN (SELECT Item, SUM(Quantity) AS Quantity FROM Pur_Orders Where Pur_Orders.Date='" + dateTimePicker1.Value.Date + "' GROUP BY Item) AS Pur_Orders ON S.Product = Pur_Orders.Item LEFT JOIN (SELECT Item, SUM(Quantity) AS Quantity FROM Sale_Orders Where Sale_Orders.Date='" + dateTimePicker1.Value.Date + "' GROUP BY Item) AS Sale_Orders ON S.Product = Sale_Orders.Item";
SqlCommand cmd = new SqlCommand(accept, obj.con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Inv_stock");
da.Fill(ds, "Pur_Orders");
da.Fill(ds, "Sale_Orders");
rpt.SetDataSource(da);
obj.con.Close();
Inventory inv = new Inventory();
inv.CrystalReportViewer.ReportSource = rpt;
inv.Visible = true;
What is problem?????
You are setting the datasource of the report with DataAdapter:
rpt.SetDataSource(da);
Replace it with a dataset or a datatable like this:
rpt.SetDataSource(ds); // a dataset
rpt.SetDataSource(ds.Tables["TableName"]); // a datatable
You should make a View of the Nested Query and Check it and then call that specific view when u are making a new Report as Datasourse.
If your Query is Correct but Datasourse is invalid you will not get you Desired output on the Report..
This is T-SQL for Inserting data from datagridview into SQL Table but the issue is that one of datagridview's column is DataGridViewComboBoxColumnand I need for each row save particular selected item in combobox. May I ask how it can be done?
public DataGridViewComboBoxColumn cbColumn;
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
try
{
string delCmdTxt = "DELETE FROM PRONAJEM WHERE NA_CISLKU=#NA_CISLKU";
SqlCommand cmdDel = conn.CreateCommand();
cmdDel.Parameters.AddWithValue("#NA_CISLKU",VybraneCisku);
cmdDel.CommandText = delCmdTxt;
cmdDel.Transaction = sqlTrans;
cmdDel.ExecuteNonQuery();
string insert_sql = "INSERT INTO PRONAJEM(DATUM,PLODINA,CENAMJ,MNOZSTVIMJ,PRIKAZ,NA_ZUSTA,NA_CISLKU,RODNECISLO)VALUES" +
"(#DATUM,#PLODINA,#CENAMJ,#MNOZSTVIMJ,#PRIKAZ,#NA_ZUSTA,#NA_CISLKU,#RODNECISLO)";
using (SqlCommand sqlcom = conn.CreateCommand())
{
sqlcom.CommandText = insert_sql;
sqlcom.Transaction = sqlTrans;
sqlcom.Parameters.Add("#DATUM", SqlDbType.Date); //Replace with whatever the correct datatypes are
sqlcom.Parameters.Add("#PLODINA", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#CENAMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#MNOZSTVIMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#PRIKAZ", SqlDbType.Date);
sqlcom.Parameters.Add("#NA_ZUSTA", SqlDbType.Decimal);
sqlcom.Parameters.Add("#NA_CISLKU", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#RODNECISLO", SqlDbType.NVarChar);
var validRows = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells["DATUM"].Value != null);
foreach (DataGridViewRow row in validRows)
{
sqlcom.Parameters[0].Value = row.Cells["DATUM"].Value;
sqlcom.Parameters[1].Value = row.Cells["POLOZKAcb"].Value;
sqlcom.Parameters[2].Value = row.Cells["CENAMJ"].Value;
sqlcom.Parameters[3].Value = row.Cells["MNOZSTVIMJ"].Value;
sqlcom.Parameters[4].Value = row.Cells["PRIKAZ"].Value;
sqlcom.Parameters[5].Value = row.Cells["NA_ZUSTA"].Value;
sqlcom.Parameters[6].Value = VybraneCisku;
sqlcom.Parameters[7].Value = VybraneRodneCislo;
sqlcom.ExecuteNonQuery();
}
sqlcom.Dispose();
}
sqlTrans.Commit();
This is the creating of DataGridViewComboBoxColumn:
string query = "SELECT * FROM PLODINY ";
SqlCommand newcom = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader= newcom .ExecuteReader();
List<string> listPlodiny = new List<string>();
while (reader.Read())
{
listPlodiny.Add(reader.GetString(reader.GetOrdinal("PLODINA")) + "-" + Decimal.Parse(reader["CENAZAQ"].ToString()).ToString());
for (int i = 0; i <= listPlodiny.Count() - 1; i++)
{
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.DataSource = listPlodiny;
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
Thank you all for your time
I think because you not set a .ValueMember property for DataGridViewComboBoxColumn...
You need to set
.ValueMember - set Value for Cell from DataSource's property.
This value will be referenced with Column.DataPropertyName's value.
.DisplayMember- Value of this will be used for diplay text in dropdown cell
Try next(updated for using of DataTable as DataSource in DataGridViewComboBoxColumn:
DataTable dtPlodiny;
using(SqlConnection sqlConn = new SqlConnection(conn))//conn - your connection string
{
string sqlQuery = #"SELECT ID, Description FROM PLODINY"; //better practice use only fields you need
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtPlodiny);
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.Name = "POLOZKAcb"
cbColumn.DataSource = dtPlodiny; //Changed with DataTable
//add next two rows
cbColumn.DisplayMember = "Description" //property from .Datasource you want to show for user
cbColumn.ValueMember = "ID" //property from .Datasource you want use as Value - reference to DataPropertyName
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
If your datagridview use always same columns,
then I think easally if you use a predefined columns(created/added through Designer). Then you can set a name for every column and use it in code as object:
this.MyColumnPolozka.Name...
for example...
if you donot get correct value from row.Cells(0).Value then try casting it to dropdownlist
I'm getting this error: Cannot bind to the new display member C#
sConn = new SqlConnection(sStr);
daSched = new SqlDataAdapter("Select Subject from Schedules where Username = '" + lblUsername.Text + "'", sConn);
dsSched = new DataSet();
daSched.Fill(dsSched, "Schedules");
dsSched.Tables["Schedules"].PrimaryKey = new DataColumn[] { dsSched.Tables["Schedules"].Columns["ScheduleID"] };
cbxSubject.DataSource = dsSched.Tables["Schedules"];
cbxSubject.DisplayMember = "Schedule";
cbxSubject.ValueMember = "ScheduleID";
cbxSubject.Text = "Choose Subject";
I don't know where went wrong. This is the preview of the table Schedules: http://i47.tinypic.com/1zzoz5z.png
Thanks for any help.
You don't have a field in your table called "Schedule", so there is no member the control can find called Schedule, and you have selected only Subject
ScheduleID is already your primary key, so you're better of changing your Sql Query to:
Select ScheduleID, Subject From... (also you probably should parameterize it)
This line -> dsSched.Tables["Schedules"].PrimaryKey = new DataColumn[] { dsSched.Tables["Schedules"].Columns["ScheduleID"] }; is unnecessary.
From what I can tell I beleive you want your display member to be the "Subject"
Also - you should Open your connection (I don't see it in your post) - and more ideally wrap it in a using statement
Something like:
using (SqlConnection con = new SqlConnection(connectionString))
{
string userName = lblUsername.Text;
con.Open();
var adapter = new SqlDataAdapter("Select ScheduleID, Subject From
Schedules Where Username = #username", conn);
adapter.Parameters.Add("#username", SqlDbType.VarChar, 50, userName)
var dsSched = new DataSet();
adapter.Fill(dsSched);
cbxSubject.DataSource = dsSched.Tables[0];
cbxSubject.DisplayMember = "Subject";
cbxSubject.ValueMember = "ScheduleID";
cbxSubject.DataBind();
}