I am using windows form to build an application using datagridview. Every data grid contains an empty row at the top and I suspect that it is the way that I am populating them but as I am coming to the end, I am reluctant to change any of my code as I am a beginner.
Is there a simple way to check if a row if empty, then set that to not visible?
The code that I am using:
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
customersDataGridView.Rows.Add();
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
rowadd.Cells[1].Value = reader["Forename"].ToString();
rowadd.Cells[2].Value = reader["Surname"].ToString();
rowadd.Cells[3].Value = reader["Address"].ToString();
rowadd.Cells[4].Value = reader["Town"].ToString();
rowadd.Cells[5].Value = reader["Postcode"].ToString();
rowadd.Cells[6].Value = reader["Date_Of_Birth"].ToString();
rowadd.Cells[7].Value = reader["Phone_Number"].ToString();
rowadd.Cells[8].Value = reader["Email"].ToString();
rowadd.Cells[9].Value = reader["Current_Rental"].ToString();
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
reader.Close();
connect.Close();
}
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
}
You could use the IsNullOrWhiteSpace. But before that, you have to check your sql statement, why you have empty rows result.
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
if (!string.IsNullOrWhiteSpace(reader["Customer_ID"].ToString()))
{
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
//Others Stuff
//...
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
}
Related
I am new to C # and have a small problem with DataGridView. I have two codes selected in my database to fill this grid with different columns. I want the user to see only the columns I select, when I start, this works perfectly, but when I try to search the other columns, I get this message: "System.ArgumentOutOfRangeException: 'index was out of range. It must be non-negative and less than the size of the collection 'Arg_ParamName_Name' "
i've tryied to clear the index columns or restart the dataviewgrid, but no success! need help!
private void ConfiguraDataGridView(int i)
{
switch (i)
{
case 1:
//setando nome do cabeçalho
dgAlmoxarifado.Columns[0].HeaderText = "Nome do Item";
dgAlmoxarifado.Columns[1].HeaderText = "Cor";
dgAlmoxarifado.Columns[2].HeaderText = "Marca";
dgAlmoxarifado.Columns[3].HeaderText = "Modelo";
dgAlmoxarifado.Columns[4].HeaderText = "Tamanho";
dgAlmoxarifado.Columns[5].HeaderText = "Quantidade";
dgAlmoxarifado.Columns[6].HeaderText = "Tipo";
dgAlmoxarifado.Columns[7].HeaderText = "Quantidade Recomendada";
dgAlmoxarifado.Columns[8].HeaderText = "Data de Cadastro";
dgAlmoxarifado.Columns[9].HeaderText = "Cadastro";
break;
case 2:
//setando nome do cabeçalho
dgAlmoxarifado.Columns[0].HeaderText = "Nome do Item";
dgAlmoxarifado.Columns[1].HeaderText = "Cor";
dgAlmoxarifado.Columns[2].HeaderText = "Marca";
dgAlmoxarifado.Columns[3].HeaderText = "Modelo";
dgAlmoxarifado.Columns[4].HeaderText = "Tamanho";
dgAlmoxarifado.Columns[5].HeaderText = "Quantidade";
dgAlmoxarifado.Columns[6].HeaderText = "Tipo";
dgAlmoxarifado.Columns[7].HeaderText = "Requisição";
dgAlmoxarifado.Columns[8].HeaderText = "Data de Requisição";
dgAlmoxarifado.Columns[9].HeaderText = "Quantidade Requisitada";
dgAlmoxarifado.Columns[10].HeaderText = "Reposição";
dgAlmoxarifado.Columns[11].HeaderText = "Data de Reposição";
dgAlmoxarifado.Columns[12].HeaderText = "Quantidade Repositada";
dgAlmoxarifado.Columns[13].HeaderText = "Observação";
break;
}
}
private void ResetDataGridView()
{
// dgAlmoxarifado.CancelEdit();
// dgAlmoxarifado.Dispose();
dgAlmoxarifado.Columns.Clear();
dgAlmoxarifado.Refresh();
dgAlmoxarifado.DataSource = null;
}
EDIT: The entire code about this event.
Load Object:
private void IEstoque_Load(object sender, EventArgs e)
{
ResetDataGridView();
dgAlmoxarifado.DataSource = mt.CarregarGrid(1, txtSearch.Text);
ConfiguraDataGridView(1);
}
Pass to BLL:
public DataTable CarregarGrid(int opcao, string nomeBusca)
{
return cb.CarregarGrid(opcao, nomeBusca);
}
Pass to DAL:
public DataTable CarregarGrid(int opcao, string nomeBusca)
{
DataTable dt = new DataTable();
string comando = string.Empty;
switch (opcao)
{
case 1:
comando = "select i.nomeItem, i.cor, i.marca, i.modelo, i.tamanho, i.quantidadeDisponivel,i.tipo, i.quantidadeRecomendada, i.cadastradoNoDia, u.nomeUsuario from itens i join movimentacao m on i.id = m.id_itens join usuarios u on u.id = m.id_usuario where i.nomeItem like #nome ";
break;
case 2:
comando = "select i.nomeItem, i.cor, i.marca, i.modelo, i.tamanho, i.quantidadeDisponivel,i.tipo, m.requisicao, m.dataRequisicao, m.quantidadeRequisitada, m.observacaoRequisicao,m.reposicao, m.dataReposicao, m.quantidadeReposicao, m.observacaoReposicao from itens i join movimentacao m on i.id = m.id_itens join usuarios u on u.id = m.id_usuario where i.nomeItem like #nome ";
break;
}
MySqlCommand cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("#nome", "%"+ nomeBusca +"%");
try
{
Conectar();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (MySqlException ex)
{
string erro = ex.Message;
return dt;
}
finally
{
Desconectar();
}
}
Then i have this button search:
private void btnSearch_Click(object sender, EventArgs e)
{
if (rdItem.Checked == true)
{
ResetDataGridView();
dgAlmoxarifado.DataSource = mt.CarregarGrid(1, txtSearch.Text);
ConfiguraDataGridView(1);
}
else if (rdMovimentacao.Checked == true)
{
ResetDataGridView();
dgAlmoxarifado.DataSource = mt.CarregarGrid(2, txtSearch.Text);
ConfiguraDataGridView(2);
}
}
When i press that button occurs the error!
Don't clear the columns, just set the DataSource to null and then set it to the corresponding DataSource.
It worked, thanks to everyone who helped, I had a problem with my select (
an error in the field name) and after following the tip from #Jannick Breunis about cleaning only the datasource and the tip from #Nbk about directly checking the filling of the Data Table was solved.
with a combo selected index changed event I am taking data from table in my labels all going well except the date. Problem: Label is showing date with 12:00 and I need only date (dd/MMM/yyyy) not with time 12:00. This date is perfect in column of table and also in gridview. Only the label shows it wrongly in the Label (AcPtRgDateLbl.Text).
here is the code:
private void AcPtPtrDd_SelectedIndexChanged(object sender, EventArgs e)
{
cmd = new SqlCommand("SELECT * FROM Patients where pt_ptr='" + AcPtPtrDd.Text.ToString() + "'", con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string idn = (string)dr["pt_name"].ToString();
string idn1 = (string)dr["pt_date"].ToString();//Problem is here Please help to solve it.
string idn4 = (string)dr["pt_aid"].ToString();
string idn9 = (string)dr["pt_phone"].ToString();
AcPtNameLbl.Text = idn;
AcPtRgDateLbl.Text = idn1;
AcPtAidLbl.Text = idn4;
AcPtPhonLbl.Text = idn9;
if (AcPtAidLbl.Text == "-")
{
AcPtAidTxt.Enabled = false;
}
else
{
AcPtAidTxt.Enabled = true;
}
}
con.Close();
}
Tabel from SQL:
ALTER procedure [dbo].[pa_getPtAccountsDataLike]
#data nvarchar(50)
as
select
p.pta_id as 'ID',
p.pta_ptr as 'PtR',
p.pta_date as 'Date',
p.pta_fee as 'Fee',
p.pta_dis as 'Discount',
p.pta_aid as 'Aid',
p.pta_rcv as 'Receive',
p.pta_bal as 'Balance'
from PtAccounts p
where
p.pta_ptr like '%'+#data+'%'
or
p.pta_date like '%'+#data+'%'
order by p.pta_ptr desc
Try read as DateTime and then represent it as a string
string idn1 = Convert.ToDateTime(dr["pt_date"]).ToString("dd/MMM/yyyy");
More code (let's brush up your solution):
//DONE: required fields only; parametrized query
string sql =
#"SELECT pt_name,
pt_date,
pt_aid,
pt_phone
FROM Patients
WHERE pt_ptr = #pt_ptr";
//DONE: wrap IDisposable in using
using (var cmd = new SqlCommand(sql, con)) {
//TODO: cmd.Parameters.Add("#pt_ptr", AcPtPtrDd.Text, Rdbms_Type_Here);
// (explicit add) is a better implementation
cmd.Parameters.AddWithValue("#pt_ptr", AcPtPtrDd.Text);
using (var dr = cmd.ExecuteReader()) {
//DONE: we read at most one record only; no need in while
if (dr.Read()) {
AcPtNameLbl.Text = Convert.ToString(dr["pt_name"]);
AcPtRgDateLbl.Text = Convert.ToDateTime(dr["pt_date"]).ToString("dd/MMM/yyyy");
AcPtAidLbl.Text = Convert.ToString(dr["pt_aid"]);
AcPtPhonLbl.Text = Convert.ToString(dr["pt_phone"]);
}
else {
//DONE: what if we have an empty cursor?
AcPtNameLbl.Text = "";
AcPtRgDateLbl.Text = "";
AcPtAidLbl.Text = "-";
AcPtPhonLbl.Text = "";
}
AcPtAidTxt.Enabled = AcPtAidLbl.Text != "-";
}
}
Please try this
string idn1 = dr["pt_date"].ToString("dd/MMM/yyyy");
I'm trying to Iterate through rows in a 2 column table to check 1 field in each row against a Name. Once found I want to code to assign the corresponding Number to the OurNumber variable, and break out of the loop by setting GotTheNumber to true.
Below is the code I'm using:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
DataTable table = new DataTable();
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
string SelectedName = DropBoxEmp.Text;
bool GotTheNumber = false;
int OurNumber = 0;
while (!GotTheNumber)
{
foreach (DataRow ThisRow in table.Rows)
{
if (SelectedName = (table.Rows[ThisRow]))
{
OurNumber = ///THATNUMBER///;
GotTheNumber = true;
}
}
}
MessageBox.Show(SelectedName);
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
form.PassValueName = SelectedName;
form.PassSelectedPayroll = GoodNumber;
form.Tag = this;
form.Show(this);
Hide();
}
I don't know where to go from the If statement, so any help would be greatly appreciated.
Looping through the rows in your client program is exactly what you don't want to do. Let the database do that work for you. Try this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
object result;
string query = "SELECT PayrollNo FROM [Employee] WHERE FirstName + ' ' + LastName = ?";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
//guessing at type and length here
cmd.Parameters.Add("?", OleDbType.VarWChar, 50).Value = DropBoxEmp.Text;
conn.Open();
result = cmd.ExecuteScalar();
}
if (result != null && result != DBNull.Value)
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = (int)result;
form.Tag = this;
form.Show(this);
Hide();
}
}
If you really want to loop through the rows against all reason (it's slower, requires writing more code, and it's more error-prone), you can do this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
DataTable table = new DataTable();
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
int PayrollNumber = 0;
foreach (DataRow ThisRow in table.Rows)
{
if (DropBoxEmp.Text == ThisRow["NAME"])
{
PayrollNumber = (int)ThisRow["PayrollNo"];
break;
}
}
//the whole loop could also be consolidated to this:
//PayrollNumber = (int)table.Rows.First(r => r["NAME"] == DropBoxEmp.Text)["PayrollNo"];
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = PayrollNumber ;
form.Tag = this;
form.Show(this);
Hide();
}
Hm, hard to guess what exactly your problem is. But I think you just want to get the PayrollNo from the current row, aren't you?
Regarding the line further down ...
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
... I think you could just call:
if (...)
{
OurNumber = ThisRow["PayrollNo"].ToString();
GotTheNumber = true;
}
However, I have no clue what you are doing with the following if-condition and if this really does what you want it to do:
if (SelectedName = (table.Rows[ThisRow]))
{
...
}
I want to be able to use this button to search oracle three times at most and after the three attempts to disable the button and use a different search. Below is my code when the button is clicked to search first. If the catch is used three times I want to be able to disable the button.
private void btnCancelSearch_Click(object sender, EventArgs e)
{
try
{
//Connect to Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
//Define SQL Query (Select)
strSQL = "SELECT * FROM Bookings WHERE BookingNo = '" + txtCnlBookingNo.Text + "'";
cmd.CommandText = strSQL;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
txtBookingNo.Text = dr.GetValue(0).ToString();
txtBkgSurname.Text = dr.GetValue(1).ToString();
txtBkgForename.Text = dr.GetValue(2).ToString();
txtBkgContactNo.Text = dr.GetValue(3).ToString();
txtBkgStreet.Text = dr.GetValue(4).ToString();
txtBkgTown.Text = dr.GetValue(5).ToString();
txtBkgCounty.Text = dr.GetValue(6).ToString();
txtBkgCountry.Text = dr.GetValue(7).ToString();
txtBkgEmail.Text = dr.GetValue(8).ToString();
cboBkgNoGuests.Text = dr.GetValue(9).ToString();
cboBkgPayment.Text = dr.GetValue(10).ToString();
dtpBkgCheckIn.Text = dr.GetValue(11).ToString();
dtpBkgCheckOut.Text = dr.GetValue(12).ToString();
}
catch
{
//Display confirmation message
MessageBox.Show("Not a valid Booking No");
}
Depending on your application. You can keep track of a variable called:
int ButtonClickedCount = 0;
increment this variable everytime the button is clicked. If the click count is exceeded you notify the user or disable the button.
Not sure if this is what you trying to achieve:
Declare a variable to keep track of the number of times user have clicked, then apply your logic?
int count = 0;
private void btnCancelSearch_Click(object sender, EventArgs e)
{
if(count <3){
count++;
try
{
//Connect to Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
//Define SQL Query (Select)
strSQL = "SELECT * FROM Bookings WHERE BookingNo = '" + txtCnlBookingNo.Text + "'";
cmd.CommandText = strSQL;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
txtBookingNo.Text = dr.GetValue(0).ToString();
txtBkgSurname.Text = dr.GetValue(1).ToString();
txtBkgForename.Text = dr.GetValue(2).ToString();
txtBkgContactNo.Text = dr.GetValue(3).ToString();
txtBkgStreet.Text = dr.GetValue(4).ToString();
txtBkgTown.Text = dr.GetValue(5).ToString();
txtBkgCounty.Text = dr.GetValue(6).ToString();
txtBkgCountry.Text = dr.GetValue(7).ToString();
txtBkgEmail.Text = dr.GetValue(8).ToString();
cboBkgNoGuests.Text = dr.GetValue(9).ToString();
cboBkgPayment.Text = dr.GetValue(10).ToString();
dtpBkgCheckIn.Text = dr.GetValue(11).ToString();
dtpBkgCheckOut.Text = dr.GetValue(12).ToString();
}
catch
{
//Display confirmation message
MessageBox.Show("Not a valid Booking No");
}
}else
{
//Implement whatever search you want here
//And disable your button here
}
}
I am trying to load data into a textbox by using a DataReader depend on the Drop down list selection. Didn't get error from this code, but the data is not loaded into textbox. please correct me.
public void text()
{
cn1.Open();
string s;
s = "select Request_Type from component where Material_Code='" + Mcodeddl.SelectedItem.Text + "' ";
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
public void MC()
{
Mcodeddl.Items.Clear();
ListItem li1 = new ListItem();
li1.Text = "-Select-";
Mcodeddl.Items.Add(li1);
Mcodeddl.SelectedIndex = 0;
cn1.Open();
string s1;
s1 = "select Material_Code from component";
SqlCommand cd1 = new SqlCommand(s1, cn1);
SqlDataReader dr1;
try
{
dr1 = cd1.ExecuteReader();
while (dr1.Read())
{
ListItem ni1 = new ListItem();
ni1.Text = dr1["Material_Code"].ToString().Trim();
Mcodeddl.Items.Add(ni1);
}
dr1.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
If everything works fine without exceptions that is mean the connection established correctly and the SQL command is correct. I think you have to make sure about your SQL statement. Maybe it returns nothing because there are no matches.
We need more explain about your issue.