Parameter add with value gives System.Data.DataRowView - c#

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.

Related

How can I return a stored procedure's result as XML?

I coded a web service connecting to MS-Sql server and getting the results from a stored procedure. My below code is getting only the first result of procedure, but I need all results in the response xml file. I think that I need to use data adapter, data reader, data fill, etc.. something like this. But I could not succeed. I would appreciate any help:
PS: Info.cs class already created.
[WebMethod]
public Info NumberSearch2(string no)
{
Info ourInfo = new Info();
string cs = ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = CommandType.StoredProcedure
};
SqlParameter parameter = new SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
}
}
return ourInfo;
}
After #David 's recommendation:
[WebMethod]
//public Info NumberSearch2(string no)
public List<Info> NumberSearch2(string no)
{
Info ourInfo = new Info();
var ourInfos = new List<Info>();
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(cs))
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
var ourInfos = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
}
return ourInfos;
}
You're returning a single Info object. If you want a collection of them, return a List<Info> instead. Change the method signature:
public List<Info> NumberSearch2(string no)
Declare the object to return:
var ourInfos = new List<Info>();
Within your loop, add each record to the list:
while (dr.Read())
{
var ourInfo = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
And return the list:
return ourInfos;

How to filter a dropdown in C#?

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;
}

Oracle SQL with parameters not working?

I'm familiar with SQL Server but new to Oracle. I'm working on doing a bulk insert or update using the Array technique I've found in some examples. However, I must be doing this incorrect because I'm getting errors about "invalid table.column". I have a feeling it has to do with the way I'm trying to assign parameter names in the in-line SQL and command parameters. In the example I've seen they use numeric values for the parameters like ":1, :2, :3" but if possible I would like to use ":paramtername1, :parametername2, :parametername3".
Here is what I'm doing
sbQuery.Append("update SAP_EMPLOYEE set ");
sbQuery.Append(" EMP_ID = :p_EmployeeId, EVENT_FROM_DT = :p_EventFromDate, EVENT_TYP = :p_EventType, EVENT_RSN = :p_EventRsn,");
sbQuery.Append(" where Emp = :p_Employee");
Then I create arrays to add the values to
string[] arrEmployee = new string[listEmployee.Count];
string[] arrEmployeeId = new string[listEmployee.Count];
DateTime[] arrEventFromDt = new DateTime[listEmployee.Count];
string[] arrEventTyp = new string[listEmployee.Count];
string[] arrEventRsn = new string[listEmployee.Count];
Populate the arrays
int i = 0;
foreach (SAP_EMPLOYEE item in listEmployee)
{
arrEmployee[i] = item.EMP;
arrEmployeeId[i] = item.EMP_ID;
if(item.EVENT_FROM_DT.HasValue)
{
arrEventFromDt[i] = item.EVENT_FROM_DT.Value;
}
arrEventTyp[i] = item.EVENT_TYP;
arrEventRsn[i] = item.EVENT_RSN;
i++;
}
Then call the connection, cmd, query
OracleConnection objConnection = new OracleConnection(connString);
using (objConnection)
{
objConnection.Open();
//create Oracle parameters and pass arrays of data
OracleParameter p_Employee = new OracleParameter();
p_Employee.OracleDbType = OracleDbType.Varchar2;
p_Employee.Value = arrEmployee;
OracleParameter p_EmployeeId = new OracleParameter();
p_EmployeeId.OracleDbType = OracleDbType.Varchar2;
p_EmployeeId.Value = arrEmployeeId;
OracleParameter p_EventFromDate = new OracleParameter();
p_EventFromDate.OracleDbType = OracleDbType.Date;
p_EventFromDate.Value = arrEventFromDt;
OracleParameter p_EventType = new OracleParameter();
p_EventType.OracleDbType = OracleDbType.Char;
p_EventType.Value = arrEventTyp;
OracleParameter p_EventRsn = new OracleParameter();
p_EventType.OracleDbType = OracleDbType.Char;
p_EventType.Value = arrEventRsn;
OracleCommand objCmd = objConnection.CreateCommand();
objCmd.CommandText = sbQuery.ToString();
objCmd.ArrayBindCount = arrEmployee.Length;
objCmd.Parameters.Add(p_Employee);
objCmd.Parameters.Add(p_EmployeeId);
objCmd.Parameters.Add(p_EventFromDate);
objCmd.Parameters.Add(p_EventType);
objCmd.Parameters.Add(p_EventRsn);
objCmd.ExecuteNonQuery();
}

while updating grid view not updating all table

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();
}
}

DataGridViewComboBoxColumn save SelectedText for each row in SQL

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

Categories

Resources