Datagridviews row count? - c#

I have this 2 Datagridviews, dgv1 and 2. How can i check if dgv2 has no "content" or rows?
For example i want to do: Send OrderID: 0001(from dgv1) to archives if dgv 2 is "empty" or no rows? basically i want to remove this Order is its dgv2 has no rows or no products left.
dgv2's content is related to dgv1's primary key btw.
private void dgvReceiving_CellClick(object sender, DataGridViewCellEventArgs e)
{
using (SqlConnection connection = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True"))
{
SqlCommand command =
new SqlCommand("select OrderID,SupplierName,LeadTime,OrderedBy,DateOrdered,Status,DateToReceived from Orders where OrderID = '" + dgvReceiving.CurrentRow.Cells[0].Value.ToString() + "'", connection);
connection.Open();
SqlDataReader read = command.ExecuteReader();
while (read.Read())
{
rorderid.Text = (read["OrderID"].ToString());
rsupplier.Text = (read["SupplierName"].ToString());
rleadtime.Text = (read["LeadTime"].ToString());
rordered.Text = (read["OrderedBy"].ToString());
rdateordered.Text = (read["DateOrdered"].ToString());
rdatedelivery.Text = (read["DateToReceived"].ToString());
rstatus.Text = (read["Status"].ToString());
}
SqlConnection cn2 = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True");
cn2.Open();
string amt = "select sum(TotalPrice) from Orders_productholder where OrderID = '" + rorderid.Text + "'";
SqlCommand cmd2 = new SqlCommand(amt, cn2);
labelsupertotal.Text = "P "+cmd2.ExecuteScalar().ToString();
}
dgvreceivingproduct();
}
private void dgvreceivingproduct()
{
SqlConnection cn3 = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True");
cn3.Open();
string qry = "Select Status,ID,ProductID,ProductName,Dosage,Price,QtyOrdered,TotalPrice,ExpirationDate,SellingPrice,BatchNumber from Orders_productholder where Status = 'Unreceived' and OrderID = '" + dgvReceiving.CurrentRow.Cells[0].Value.ToString() + "' ";
SqlCommand cmd3 = new SqlCommand(qry, cn3);
DataTable poholder = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd3);
adapter.Fill(poholder);
dgvReceivingproducts.DataSource = poholder;
}

use the property (dgv2.RowCount > 0)

Related

C# multi valued combo box value to SQL Server database

private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}

while opening the page getting error there is no row at position 0

I am trying to open feedback form but showing below error
"There is no row at position 0."
I have already checked database, there is a row for this query "select zzfname from sap_empmst where pernr = "
Here is my code...
public partial class feedback : System.Web.UI.Page
{
DataAccess Getdata=new DataAccess();
OracleConnection con = new OracleConnection("Data Source=cluster;User ID=ocgpis;Password=pisocg;unicode=true");
OracleConnection con1 = new OracleConnection("Data Source=oragc;User ID=ipcltos;Password=ipcltos;unicode=true");
//OracleConnection con = new OracleConnection("Data Source=10.127.240.231/ocgpis;User ID=ocgpis;Password=pisocg;unicode=true");
//OracleConnection con1 = new OracleConnection("Data Source=10.127.240.216/ipcldb;User ID=ipcltos;Password=ipcltos;unicode=true");
OracleConnection con2 = new OracleConnection("Data Source=cluster;User ID=RGSS;Password=RGSS;unicode=true");
string strMessage = ""; int mins_now = 0;
protected void Page_Load(object sender, EventArgs e)
{
Label1_pl.Text = Session["UserID"].ToString();
string sqlstr = "select zzfname from sap_empmst where pernr = '" + Label1_pl.Text + "'";
DataSet ds = new DataSet();
OracleDataAdapter adp = new OracleDataAdapter(sqlstr, con1);
adp.Fill(ds);
string zzfname = ds.Tables[0].Rows[0].ItemArray[0].ToString();
Label2_name.Text = zzfname;
}
Please help, thanks in advance
Try this
Error Says that Your are accessing a row which is Not present so,
Always Check For whether Row exists in DataSet/DataTable using RowCount
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Label1_pl.Text = Session["UserID"].ToString();
string sqlstr = "select zzfname from sap_empmst where pernr = '" +
Label1_pl.Text + "'";
DataSet ds = new DataSet();
OracleDataAdapter adp = new OracleDataAdapter(sqlstr, con1);
adp.Fill(ds);
if(ds!=null)
if(ds.Tables[0].Rows.Count>0)
{
string zzfname = ds.Tables[0].Rows[0]["zzfname"].ToString();
Label2_name.Text = zzfname;
}
}
}

Categories from 2 ComboBox affecting third Combobox for datagridview with SQL

To put it into short story
i wanted something like "SELECT companyName FROM table where mainCategory = firstcombobox and subcategory = secondcombobox" , how do i do the sql query?
==========================
Long story
I have created a form , with a working coding , but i need an extra assistance.
Somewhat , i am stuck on trying to figure out how to let the 3rd combobox value , determined by the first and second.
and what i wanted is , something like , getting the value of Main Category and Sub category to effect the list of the third combo box.
i just need the SQL query , such as : "SELECT companyName FROM table where maincategory = firstcombobox and subcategory = secondcombobox"
and then shows the company name within the picks of main and sub category.
Like this :
For the Main Category and Sub-Category , i have it working with this code.
This code also includes the 3rd ComboBox code which right now operates without the first and second combobox attached to the 3rd combobox code.
public partial class User : Form
{
Dictionary<string, List<string>> Category = new Dictionary<string, List<string>>();
DataSet ds1;
public User()
{
InitializeComponent();
}
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
ds1 = new DataSet();
daMain.Fill(ds1, "Maincate");
DataTable dt = ds1.Tables["MAINCATE"];
foreach (DataRow dr in dt.Rows)
{
List<string> SubCats = new List<string>
{
dr["Subcat1"].ToString(),
dr["Subcat2"].ToString(),
dr["Subcat3"].ToString(),
dr["Subcat4"].ToString()
};
Category.Add(dr["mainCate"].ToString(), SubCats);
mainCatU.Items.Add(dr["mainCate"].ToString());
}
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
//**Code for third combobox**
SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
DataTable dt1 = new DataTable();
ListU.DataSource = dt1;
daSearch.Fill(dt1);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
//**----------------------**
conn.Close();
}
private void mainCatU_SelectedIndexChanged(object sender, EventArgs e)
{
if(Category.ContainsKey(mainCatU.SelectedItem.ToString()))
{
subCatU.DataSource = Category[mainCatU.SelectedItem.ToString()];
}
}
and the databases are as shown :
dbo.MAINCATE
dbo.ComDet
and the code for the View Selected Company button is :
private void searchBtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName = #cName", conn);
daS.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dts3 = new DataTable();
daS.Fill(dts3);
dataGridView1.DataSource = dts3.DefaultView;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
conn.Close();
}
again , right now the third combo box is coded to run without the maincategory and subcategory
========================
Answered - Created a button called search , and took the coding from form load into the button , added with SQLCon , and added the SQLQuery needed..
Thx guys.. :)
private void button2_Click_1(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
string myRequest = "SELECT cName FROM ComDet where mainCate = '" + mainCatU.SelectedItem.ToString() + "' and Subcat = '" + subCatU.SelectedItem.ToString() + "'";
SqlDataAdapter daSearch = new SqlDataAdapter(myRequest, conn);
DataTable dtSea = new DataTable();
ListU.DataSource = dtSea;
daSearch.Fill(dtSea);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
}
Try calling following function on SelectedValue change event of mainCatU and subCatU combo:
private void SetCompanyList()
{
if (string.IsNullOrEmpty(Convert.ToString(mainCatU.SelectedValue)) || string.IsNullOrEmpty(Convert.ToString(subCatU.SelectedValue))) return;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daMain = new SqlDataAdapter("SELECT cName FROM ComDet where mainCate = #mainCat subCat = #subCate", conn);
daMain.SelectCommand.Parameters.Add("#mainCat", SqlDbType.VarChar).Value = mainCatU.SelectedValue;
daMain.SelectCommand.Parameters.Add("#subCate", SqlDbType.VarChar).Value = subCatU.SelectedValue;
DataTable _table = new DataTable();
daMain.Fill(_table);
ListU.DataSource = _table;
}
you have to use by the following query:
SELECT companyName FROM table where mainCategory = '" + mainCatU.selectedValue + "' and subcategory = '" + subCatU.selectedValue + "'"

How can I query a DataGridView using SQL?

I need to query a DataGridView using SQL but don't show to DataGridView.
public chkTime()
{
InitializeComponent();
}
HRTaffDataContext db = new HRTaffDataContext();
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
string strDate;
private void chkTime_Load(object sender, EventArgs e)
{
connStr();
return;
}
public void connStr()
{
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "SELECT [filesTA].EmpNo,[Employee].[First Name],[filesTA].ChkDate,[filesTA].ChkIn,[filesTA].ChkOut,[CompanyData].ShortName"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ErrorCode = 0"; // It's work
+ " WHERE [filesTA].ErrorCode = 0 and [filesTA].ChkDate ='" + dateTimePicker.Text.ToString() + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds.Tables[0];
}
"WHERE [filesTA].ErrorCode = 0" works fine.
"WHERE [filesTA].ErrorCode = 0 and [filesTA].ChkDate ='" + dateTimePicker.Text.ToString() + "'" does not work.
I need to set where DateTime.
$dateTimePicker.Text returns a string for human reading and your server maybe don't like it.
Try something like:
string sql = string.Format("SELECT [filesTA].EmpNo,[Employee].[First Name],[filesTA].ChkDate,[filesTA].ChkIn,[filesTA].ChkOut,[CompanyData].ShortName"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ErrorCode = 0 and [filesTA].ChkDate ='{0}-{1}-{2}'",
dateTimePicker.Value.Year,
dateTimePicker.Value.Month,
dateTimePicker.Value.Day);
You need to use dateTimePicker.Value.ToString() instead of dateTimePicker.Text.ToString()
A simple example of using this can be dateTimePicker.Value.ToString("yyyy-MM-dd")

Datagrid filter in c# using sql server

How to filter data in datagrid for example if you select the combo box in student number then input 1001 in the text field. All records in 1001 will appear in datagrid. I am using sql server
private void button2_Click(object sender, EventArgs e)
{
if (cbofilter.SelectedIndex == 0)
{
string sql;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds1 = new DataSet();
ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
sql = "Select * from Test where STUDNO like '" + txtvalue.Text + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds1);
dbgStudentDetails.DataSource = ds1;
dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
dbgStudentDetails.Refresh();
}
else if (cbofilter.SelectedIndex == 1)
{
//string sql;
//SqlConnection conn = new SqlConnection();
//conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
//SqlDataAdapter da = new SqlDataAdapter();
//DataSet ds1 = new DataSet();
//ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
//sql = "Select * from Test where Name like '" + txtvalue.Text + "'";
//SqlCommand cmd = new SqlCommand(sql,conn);
//cmd.CommandType = CommandType.Text;
//da.SelectCommand = cmd;
//da.Fill(ds1);
// dbgStudentDetails.DataSource = ds1;
//dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
//ds.Tables[0].DefaultView.RowFilter = "Studno = + txtvalue.text + ";
dbgStudentDetails.DataSource = ds.Tables[0];
dbgStudentDetails.Refresh();
}
}
It's difficult to answer pricisely to a vague question. I guess that you'll have to adapt your SQL query with a WHERE statement containing the user input.
If 'student number' is selected in the combo box, query like this (numbers starting with):
SELECT id, name, number FROM students WHERE number LIKE #search + '%'
If 'student name' is selected, use another query (names containing):
SELECT id, name, number FROM students WHERE name LIKE '%' + #search + '%'
Please explain in what sense C# is concerned.
You don't say what is wrong with the code you commented out. You also don't say what type the Studno column is.
Have you tried something like:
ds1.Tables[0].DefaultView.RowFilter = "Studno = '" + txtvalue.text + "'";

Categories