I have table called TBL_PRODUCTS
CREATE TABLE TBL_PRODUCTS
(
Products_ID varchar(50) PRIMARY KEY,
Products_Name varchar(100) NOT NULL,
Products_Categorys_ID int,
Products_Qty DECIMAL(16,0),
Products_Sales_Price DECIMAL(16,0),
Products_Cost_Price DECIMAL(16,0)
);
and I have a datagridview on my windows application which has 6 columns:
(Products_ID, Products_Name, Products_Categorys_Name, Products_Qty, Products_Sales_Price, Products_Total)
I want the user when he write on the 1st column (Products_ID) the code of the product it show on the same row the other details on that row like (Products_Name, Products_Categorys_Name, Products_Sales_Price) and so on ...
How I can make something like that?
I have tried this code:
SqlConnection con = new SqlConnection("Data Source=GMCADIOM-PC;Initial Catalog=TEMP;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
string sqlqry = "SELECT [Products_ID] as 'كود المنتج',[Products_Name] as 'اسم المنتج',Products_Categorys_Name as 'اسم الصنف',[Products_Qty] as 'الكميه المتاحه',[Products_Sales_Price] as 'سعر البيع',[Products_Cost_Price] as 'سعر الشراء' FROM TBL_PRODUCTS INNER JOIN TBL_PRODUCTS_CATEGORYS ON TBL_PRODUCTS_CATEGORYS.Products_Categorys_ID=TBL_PRODUCTS.Products_Categorys_ID WHERE [Products_ID] LIKE '"+ dgvBillsList.CurrentRow.Cells[0].Value.ToString()+ "'";
SqlCommand cmd = new SqlCommand(sqlqry, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
try
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dgvBillsList.CurrentRow.Cells["Products_ID"].Value = dt.Rows[i]["كود المنتج"];
dgvBillsList.CurrentRow.Cells["Products_Name"].Value = dt.Rows[i]["اسم المنتج"];
dgvBillsList.CurrentRow.Cells["Products_Categorys_Name"].Value = dt.Rows[i]["اسم الصنف"];
dgvBillsList.CurrentRow.Cells["Products_Sales_Price"].Value = dt.Rows[i]["سعر البيع"];
}
}
else
{
var result = MessageBox.Show("هذا المنتج غير موجود بقاعده البيانات ، هل تريد اضافته ؟؟", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
frmProductsNew frm = new frmProductsNew();
frm.StartPosition = FormStartPosition.CenterScreen;
frm.ShowDialog();
}
else if (result == DialogResult.No)
{
//dgvBillsList.CurrentRow.Cells[0].Value = null;
//dgvBillsList.CurrentRow.Cells[0].Selected = true;
//dgvBillsList.CurrentCell = dgvBillsList.CurrentRow.Cells[0];
//dgvBillsList.CurrentCell.Selected = true;
//dgvBillsList.BeginEdit(true);
//dgvBillsList.CurrentCell = dgvBillsList.Rows[dgvBillsList.Rows.Count].Cells[0];
}
}
CONF_Calculate.Calculate_DGV_Products(dgvBillsList);
CONF_Calculate.Calculate_DGV_Total(dgvBillsList, txtBillsAmount);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
but it gives me errors on the query side
Object reference not set to an instance of an object on
dgvBillsList.CurrentRow.Cells[0].Value.ToString()
Related
A function in my app is returning a data table by joining the data tables getting from many other sub functions. Each sub functions are independent to each other with common primary key. Now, It takes nearly two minutes to execute the function for 50 of students. Please suggest me a best/fastest way to achieve the same.
public DataTable ShowReportOnGridivew(int class_id, string searchDate)
{
DataTable dt_students_List = null;
try
{
//====Main Table=====//
dt_students_List = GetDistinctStudentList(class_id);//there will be around minimum of 50 students
if (dt_students_List != null)
dt_students_List.PrimaryKey = new DataColumn[] { dt_students_List.Columns["student_id"] };
//Tables need to merge with main table
DataTable dt_CurrentRank = null;
DataTable dt_ScoreInEnglish = null;
DataTable dt_AcademicDetails = null;
DataTable dt_ExtraCurriculam = null;
DataTable dt_Attendance = null;
DataTable dt_Arts = null;
DataTable dt_FuelToBridger = null;
DataTable dt_FuelToAircraft = null;
DataTable dt_TeacherFeedback = null;
DataTable dt_TotalScore = null;
foreach (DataRow row in dt_students_List.Rows)
{
string student_id = row["student_id"].ToString();//primary key
//==========Current Rank================//
dt_CurrentRank = GetCurrentRank(student_id);//Binding data using sql
dt_CurrentRank.PrimaryKey = new DataColumn[] { dt_CurrentRank.Columns["student_id"] };
if (dt_CurrentRank != null)
{
dt_students_List.Merge(dt_CurrentRank);
}
//====== Score in English =====
dt_ScoreInEnglish = GetScoreInEnglish(student_id, searchDate);
dt_ScoreInEnglish.PrimaryKey = new DataColumn[] { dt_ScoreInEnglish.Columns["student_id"] };
if (dt_ScoreInEnglish != null)
{
dt_students_List.Merge(dt_ScoreInEnglish);
}
//====== Academic Details =====
dt_AcademicDetails= GetAcademicDetails(student_id);
dt_AcademicDetails.PrimaryKey = new DataColumn[] { dt_AcademicDetails.Columns["student_id"] };
if (ddt_AcademicDetails != null)
{
dt_students_List.Merge(dt_AcademicDetails);
}
//=====Similarly calling other functions and merging the columns to dt_students_List ======
}
}
catch (Exception show_error)
{
string log_data = "Response: Error- " + show_error.ToString();
obj.DatalogFile("StudentsList", log_data);
throw show_error;
}
return dt_students_List;
}
====== Each sub functions are written like below.=============
private async DataTable GetCurrentRank(string student_id)
{
DataTable dt = null;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = null;
SqlDataReader dr = null;
string sql = string.Empty;
sql = "SELECT student_id,current_rank FROM student_details WHERE " +
" student_id = #student_id ";
cmd = new SqlCommand(sql, con);
con.Open();
try
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#student_id", student_id);
dr = cmd.ExecuteReader();
dt = new DataTable("CurrentRank");
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("student_id", typeof(int)),
new DataColumn("current_rank", typeof(float))});
if (dr.HasRows)
{
dt.Load(dr);
}
string log_data = "Web App Function: GetCurrentRank \n";
log_data += "Response: " + JsonConvert.SerializeObject(dt);
obj.DatalogFile("GetCurrentRank", log_data);
return dt;
}
catch (Exception show_error)
{
string log_data = "Response: Error- " + show_error.ToString();
obj.DatalogFile("GetCurrentRank", log_data);
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
You can write multiple select statement in single stored procedure;
and get output in DataSet.
You can get all your tables in a single request:
CREATE PROCEDURE Demo
**Parameters**
AS
-- Your all functions select statements
GO;
C#:
public DataSet GetDataSet(string ConnectionString, string SpName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SpName;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
I'm having trouble inserting data into my table called "client" in my database called "vet".
I'm trying to do the connection manually as opposed to using the database wizard. I want to do it this way so that i can hide the majority of my code in a separate class.
I have a feeling I have the logic for this all wrong as I'm not making use of a data set, I was hoping someone could point me in the right direction.
This is for a school assignment and not for real world use. I have read a number of similar posts but am still unable to come to a solution.
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
DataSet ds = new DataSet();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = ds.Tables["client"].NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
A DataSet is a collection of DataTables. In your example, you're only referring to one table. The SqlDataAdapter.Fill method will populate either DataSet or DataTable. You're calling da.Fill(client) which is fine - it will fill the DataTable client. You could also call da.Fill(ds, "client") which will fill the DataSet ds. You can then extract your table via ds.Tables["client"]. Using a DataSet in this example is overkill, but you can show your tutor how a DataSet works.
You're filling the DataTable but then adding the new row with reference to the DataSet. But in your example, the DataSet ds has nothing in it, because you filled the DataTable not the DataSet. Try this:
DataSet ds = new DataSet();
string commandString = "SELECT TOP 0 * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(ds, "client");
DataTable client = ds.Tables["client"];
DataRow newClientRow = client.NewRow();
... ... ...
client.Rows.Add(newClientRow);
builder.GetInsertCommand();
da.Update(client);
If you only want to insert a row, you don't need to SELECT all the rows. If you SELECT TOP 0 * from client you'll get the column names (which you need) but without the overhead of returning all the rows.
Try something like this:
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = client.NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
I can't tell what the source of your data is. Anyway, here are two examples of moving data from a CSV file to SQL Server and from a DataGridView to SQL Server.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Configuration;
public class Form1
{
private void Button1_Click(System.Object sender, System.EventArgs e)
{
dynamic headers = (from header in DataGridView1.Columns.Cast<DataGridViewColumn>()header.HeaderText).ToArray;
dynamic rows = from row in DataGridView1.Rows.Cast<DataGridViewRow>()where !row.IsNewRowArray.ConvertAll(row.Cells.Cast<DataGridViewCell>.ToArray, c => c.Value != null ? c.Value.ToString : "");
string str = "";
using (IO.StreamWriter sw = new IO.StreamWriter("C:\\Users\\Excel\\Desktop\\OrdersTest.csv")) {
sw.WriteLine(string.Join(",", headers));
//sw.WriteLine(String.Join(","))
foreach (void r_loopVariable in rows) {
r = r_loopVariable;
sw.WriteLine(string.Join(",", r));
}
sw.Close();
}
}
private void Button2_Click(System.Object sender, System.EventArgs e)
{
//Dim m_strConnection As String = "server='Server_Name';Initial Catalog='Database_Name';Trusted_Connection=True;"
//Catch ex As Exception
// MessageBox.Show(ex.ToString())
//End Try
//Dim objDataset1 As DataSet()
//Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
//Dim da As OdbcDataAdapter
System.Windows.Forms.OpenFileDialog OpenFile = new System.Windows.Forms.OpenFileDialog();
// Does something w/ the OpenFileDialog
string strFullPath = null;
string strFileName = null;
TextBox tbFile = new TextBox();
// Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";
// Shows only .csv files
OpenFile.Title = "Browse to file:";
// Title at the top of the dialog box
// Makes the open file dialog box show up
if (OpenFile.ShowDialog() == DialogResult.OK) {
strFullPath = OpenFile.FileName;
// Assigns variable
strFileName = Path.GetFileName(strFullPath);
// Checks to see if they've picked a file
if (OpenFile.FileNames.Length > 0) {
tbFile.Text = strFullPath;
// Puts the filename in the textbox
// The connection string for reading into data connection form
string connStr = null;
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt ";
// Sets up the data set and gets stuff from .csv file
OdbcConnection Conn = new OdbcConnection(connStr);
DataSet ds = default(DataSet);
OdbcDataAdapter DataAdapter = new OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn);
ds = new DataSet();
try {
DataAdapter.Fill(ds, strFileName);
// Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName);
// ..according to data source
// Catch and display database errors
} catch (OdbcException ex) {
OdbcError odbcError = default(OdbcError);
foreach ( odbcError in ex.Errors) {
MessageBox.Show(ex.Message);
}
}
// Cleanup
OpenFile.Dispose();
Conn.Dispose();
DataAdapter.Dispose();
ds.Dispose();
}
}
}
private void Button3_Click(System.Object sender, System.EventArgs e)
{
SqlConnection cnn = default(SqlConnection);
string connectionString = null;
string sql = null;
connectionString = "data source='Server_Name';" + "initial catalog='Database_Name';Trusted_Connection=True";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM [Order Details]";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
DataGridView1.DataSource = ds.Tables(0);
cnn.Close();
}
private void ProductsDataGridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == DataGridView1.Columns(3).Index && e.Value != null) {
//
if (Convert.ToInt32(e.Value) < 10) {
e.CellStyle.BackColor = Color.OrangeRed;
e.CellStyle.ForeColor = Color.LightGoldenrodYellow;
}
//
}
//
}
//Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object, _
// ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
// Handles DataGridView1.CellFormatting
// '
// If e.ColumnIndex = DataGridView1.Columns("DataGridViewTextBoxColumn8").Index _
// AndAlso e.Value IsNot Nothing Then
// '
// If CInt(e.Value) < 5 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
// '
// End If
// '
//End Sub
//If e.ColumnIndex = ProductsDataGridView.Columns(4).Index _
//AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
// ''To (you need to change the column name)
// If e.ColumnIndex = ProductsDataGridView.Columns("YourColumnName").Index _
// AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
private void Button4_Click(System.Object sender, System.EventArgs e)
{
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("FName");
tblReadCSV.Columns.Add("LName");
tblReadCSV.Columns.Add("Department");
TextFieldParser csvParser = new TextFieldParser("C:\\Users\\Excel\\Desktop\\Employee.txt");
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true)) {
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
SqlConnection con = new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;");
string strSql = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)";
//Dim con As New SqlConnection(strCon)
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName");
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName");
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department");
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
}
private void Button5_Click(System.Object sender, System.EventArgs e)
{
string SQLConnectionString = "Data Source=Excel-PC\\SQLEXPRESS;" + "Initial Catalog=Northwind;" + "Trusted_Connection=True";
// Open a connection to the AdventureWorks database.
using (SqlConnection SourceConnection = new SqlConnection(SQLConnectionString)) {
SourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand CommandRowCount = new SqlCommand("SELECT COUNT(*) FROM dbo.Orders;", SourceConnection);
long CountStart = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", CountStart);
// Get data from the source table as a AccessDataReader.
//Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
// "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
// "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + "C:\\Users\\Excel\\Desktop\\" + ";" + "Extended Properties=\"Text;HDR=No\"";
System.Data.OleDb.OleDbConnection TextConnection = new System.Data.OleDb.OleDbConnection(ConnectionString);
OleDbCommand TextCommand = new OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection);
TextConnection.Open();
OleDbDataReader TextDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess);
// Open the destination connection.
using (SqlConnection DestinationConnection = new SqlConnection(SQLConnectionString)) {
DestinationConnection.Open();
// Set up the bulk copy object.
// The column positions in the source data reader
// match the column positions in the destination table,
// so there is no need to map columns.
using (SqlBulkCopy BulkCopy = new SqlBulkCopy(DestinationConnection)) {
BulkCopy.DestinationTableName = "dbo.Orders";
try {
// Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
// Close the AccessDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the Using block.
TextDataReader.Close();
}
}
// Perform a final count on the destination table
// to see how many rows were added.
long CountEnd = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
//Console.WriteLine("Ending row count = {0}", CountEnd)
//Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
}
}
//Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
//Dim TextLine As String
//If System.IO.File.Exists(FILE_NAME) = True Then
// Dim objReader As New System.IO.StreamReader(FILE_NAME)
// Do While objReader.Peek() <> -1
// TextLine = TextLine & objReader.ReadLine() & vbNewLine
// Loop
//Else
// MsgBox("File Does Not Exist")
//End If
//Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
//Dim cmd As New SqlCommand
//cmd.Connection = cn
//cmd.Connection.Close()
//cmd.Connection.Open()
//cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
//cmd.ExecuteNonQuery()
//cmd.Connection.Close()
}
private void Button6_Click(System.Object sender, System.EventArgs e)
{
// Define the Column Definition
DataTable dt = new DataTable();
dt.Columns.Add("OrderID", typeof(int));
dt.Columns.Add("CustomerID", typeof(string));
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("OrderDate", typeof(System.DateTime));
dt.Columns.Add("RequiredDate", typeof(System.DateTime));
dt.Columns.Add("ShippedDate", typeof(System.DateTime));
dt.Columns.Add("ShipVia", typeof(int));
dt.Columns.Add("Freight", typeof(decimal));
dt.Columns.Add("ShipName", typeof(string));
dt.Columns.Add("ShipAddress", typeof(string));
dt.Columns.Add("ShipCity", typeof(string));
dt.Columns.Add("ShipRegion", typeof(string));
dt.Columns.Add("ShipPostalCode", typeof(string));
dt.Columns.Add("ShipCountry", typeof(string));
using (cn == new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;")) {
cn.Open();
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\\Users\\Excel\\Desktop\\OrdersTest.csv");
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = dt.NewRow();
for (currColumn = 0; currColumn <= dt.Columns.Count - 1; currColumn++) {
sqlColumnDataType = dt.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
dt.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
//Return False
} finally {
dr = null;
}
}
using (SqlBulkCopy copy = new SqlBulkCopy(cn)) {
copy.DestinationTableName = "[dbo].[Orders]";
copy.WriteToServer(dt);
}
}
}
public static bool GetCsvData(string CSVFileName, ref DataTable CSVTable)
{
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName);
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = CSVTable.NewRow();
for (currColumn = 0; currColumn <= CSVTable.Columns.Count - 1; currColumn++) {
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
CSVTable.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
return false;
} finally {
dr = null;
}
}
reader.Close();
reader.Dispose();
return true;
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: #telerik
//Facebook: facebook.com/telerik
//=======================================================
I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences
In my Page I am fetching a value from the Database & filling the values in the DataTable. I am then comparing that values with the mac String in the IF.
Based upon the condition in the Query there will be no records fetched, it is stuck in the IF condition and throws the No row at Position 0 Exception rather than going into the Else part.
My code is:
string mac = GetMac();
string Qry = "Select VUserid,Password from passtable where VUserid='" + UserName.Text + "' and Flag='A'";
string qry = "Select VUserid,Password from passtable where Flag='A'";
string strq = "Select Mac_id from Sysinfo Where Appflag='A'";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EvalCon"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand(Qry, conn);
SqlCommand cmd1 = new SqlCommand(qry, conn);
SqlCommand cmd2 = new SqlCommand(strq, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataAdapter daa = new SqlDataAdapter(cmd1);
SqlDataAdapter dap = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
DataTable dtt = new DataTable();
DataTable tab = new DataTable();
da.Fill(dt);
daa.Fill(dtt);
dap.Fill(tab);
for (int i = 0; i < tab.Rows.Count; i++)
{
for (int x = 0; x <= dtt.Rows.Count - 1; x++)
{
if (mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0)
{
if (UserName.Text == dtt.Rows[x]["VUserid"].ToString() && Password.Text == dtt.Rows[x]["Password"].ToString())
{
Response.Redirect("~/Changepass.aspx");
break;
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Username or Password !!!";
}
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Access Point for Evaluation !!!";
}
}
}
}
finally
{
conn.Close();
conn.Dispose();
}
}
First of all, you may want to give some more meaningful names to your variables.
On a side note, you may want to change your for loops into a foreach loop:
foreach (DataRow tabRow in tab.Rows.Count)
{
foreach (DataRow dttRow in dtt.Rows.Count)
{
// logic here
// tab.Rows[i]["Mac_id"] becomes tabRow["Mac_id"]
// and
// dtt.Rows[x]["VUserid"] becomes dttRow["VUserid"]
// and so on...
}
}
This way if there are no records fetched it won't go in.
After that, you may want to check the conditions on RowCount > 0 for the datatables before going inside the loops and act outside the loop if the RowCount is 0.
Just swap your OR condition in If statement:
if (tab.Rows.Count != 0 || mac == tab.Rows[i]["Mac_id"].ToString())
{
...
...
}
If you need to check against a null result I'd wrap my if statement in another if statement that does a simple check for a null result before doing anything else. Something like this will check if it's not null:
if(tab.rows[i]["Mac_id"] != null)
{
//logic here
}
You could add this into your current if statement check so:
if(mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0)
becomes:
if(mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0 && tab.rows[i]["Mac_id"] != null)
Though as Tallmaris says it might be better to restructure it using a foreach loop instead.
Below 2 links give the preview of my sample application.
http://img812.imageshack.us/i/image1adl.jpg/ : shows mine sample application. All fields are self explanatory (if query, let me know)
http://img834.imageshack.us/i/image2vc.jpg/ : shows, when clicked the "Edit" button from the grid, the timings are shown correctly but the order gets disturbed. (See 7:00 coming on the top and then the timings list are seen).
My Questions
How to correct the timings problem? (Link # 2)
Code for "Edit" is below
protected void lnkEdit_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt16((sender as Button).CommandArgument);
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE IsDeleted=0 and Imageid='"+ imageid +"'";
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtImageName.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
chkIsActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"].ToString());
ddlStartTime.DataSource = ds;
ddlStartTime.DataTextField = ds.Tables[0].Columns["StartTime"].ColumnName.ToString();
ddlStartTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlStartTime.DataBind();
ddlEndTime.DataSource = ds;
ddlEndTime.DataTextField = ds.Tables[0].Columns["EndTime"].ColumnName.ToString();
ddlEndTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlEndTime.DataBind();
BindDropDownList();
IsEdit = true;
}
When i edit the existing record in the grid, i am getting the values, but the record is not being updated but added as a new record into db. I am aware that i am suppose to write update script. But where to write that?
Below the code is for the same;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string strImageName = txtImageName.Text.ToString();
int IsActive = 1;
if (chkIsActive.Checked)
IsActive = 1;
else
IsActive = 0;
string startDate = ddlStartTime.SelectedItem.Text;
string endDate = ddlEndTime.SelectedItem.Text;
if ( Convert.ToDateTime(endDate) - Convert.ToDateTime(startDate) > new TimeSpan(2, 0, 0) || Convert.ToDateTime(endDate)- Convert.ToDateTime(startDate) < new TimeSpan(2,0,0))
{
//Response.Write(#"<script language='javascript'> alert('Difference between Start Time and End Time is 2 hours'); </script> ");
lblHours.Visible = true;
lblHours.Text = "Difference between Start Time and End Time should be 2 hours";
return;
}
if (checkConflictTime())
{
lblMessage.Visible = true;
lblMessage.Text = "Time Conflict";
return;
}
//if (checkTimeBetween())
//{
//}
if (fuFileUpload.PostedFile != null && fuFileUpload.PostedFile.FileName != "")
{
lblHours.Visible = false;
byte[] imageSize = new Byte[fuFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadedImage = fuFileUpload.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)fuFileUpload.PostedFile.ContentLength);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
SqlCommand cmd = new SqlCommand();
if (IsEdit == false)
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconn;
SqlParameter ImageName = new SqlParameter("#img_name", SqlDbType.NVarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter ActualImage = new SqlParameter("#img_content", SqlDbType.VarBinary);
ActualImage.Value = imageSize;
cmd.Parameters.Add(ActualImage);
SqlParameter DeletedImage = new SqlParameter("#IsDeleted", SqlDbType.Bit);
DeletedImage.Value = 0;
cmd.Parameters.Add(DeletedImage);
SqlParameter IsActiveCheck = new SqlParameter("#IsActive", SqlDbType.Bit);
IsActiveCheck.Value = IsActive;
cmd.Parameters.Add(IsActiveCheck);
SqlParameter StartDate = new SqlParameter("#StartTime", SqlDbType.NVarChar, 100);
StartDate.Value = startDate;
cmd.Parameters.Add(StartDate);
SqlParameter EndDate = new SqlParameter("#EndTime", SqlDbType.NVarChar, 100);
EndDate.Value = endDate;
cmd.Parameters.Add(EndDate);
sqlconn.Open();
int result = cmd.ExecuteNonQuery();
sqlconn.Close();
if (result > 0)
{
lblMessage.Visible = true;
lblMessage.Text = "File Uploaded!";
gvImages.DataBind();
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
}
Please help!
Where do you define Bool/Bolean IsEdit? I think its value is reset on page postback, that's why it is always false and the record is being inserted. I would suggest you to use a hidden field to track this and set its value there and check the value upon insert/updating. Finally it will be something like...
if (ds.Tables[0].Rows.Count > 0)
{
//your code
hiddenField.Value = "true"; // you can set default value to false
}
and then after
if (hiddenField.Value == "false")
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}