The code:
private void suppPopulate()
{
byCode.Text = "Supplier Code";
byDesc.Text = "Supplier";
DGViewListItems.Columns.Add("custcode", "Customer Code");
DGViewListItems.Columns.Add("customer", "Customer");
DGViewListItems.Columns[0].ReadOnly = true;
DGViewListItems.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
DGViewListItems.Columns[1].ReadOnly = true;
DGViewListItems.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
using (SqlConnection con = db.Connect())
{
SqlDataReader rd;
SqlCommand cmd = new SqlCommand("SELECT DISTINCT custcode, custname FROM Customers WHERE type = 'V';", db.Connect());
rd = cmd.ExecuteReader();
int i = 0;
if (rd.HasRows)
{
while (rd.Read())
{
DGViewListItems.Rows.Add();
DGViewListItems.Rows[i].Cells["custcode"].Value = rd["custcode"].ToString().Trim();
DGViewListItems.Rows[i].Cells["customer"].Value = rd["custname"].ToString().Trim();
}
}
cmd.Connection.Close();
}
}
The SSMS output:
The output form loads slowly, the rows for the query are over 1000 so I think the cause of the slow load is the number of returned rows? If yes, how do make the load of the datagridview faster?
NOTE - this answer relates to the first part of the original question regarding why only a single row of the DataGrid being populated.
Incrementing the counter "i" at the bottom of the while loop looks like it may fix the problem.
You are adding rows, but only updating the first.
I am receiving this sql error there is no row at position - 1.
This is what I have done.
void showData(int index)
{
Connection con = new OrderManager.Connection();
SqlDataAdapter sda = new SqlDataAdapter("Select * from [MasterDatabase].[dbo].[Neworder] Where OrderID = '" + TxtBox_OrderID.Text + "'", con.ActiveCon());
dt = new DataTable();
sda.Fill(dt);
TxtBox_OrderID.Text = dt.Rows[index][0].ToString();
ClearTextBoxes();
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["OrderID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["Date"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["Customer_Name"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["Product_Name"].ToString();
dataGridView1.Rows[n].Cells[5].Value = item["Product_Color"].ToString();
dataGridView1.Rows[n].Cells[6].Value = item["Product_PCs"].ToString();
dataGridView1.Rows[n].Cells[7].Value = item["Product_Cutting"].ToString();
dataGridView1.Rows[n].Cells[8].Value = item["Product_TotalYards"].ToString();
}
label12.Text = "Row Count: " + dt.Rows.Count.ToString();
}
I want to display only those records while navigating whose OrderID is equals to the order ID in the database.
I think your error happens on this line
TxtBox_OrderID.Text = dt.Rows[index][0].ToString();
this is not an SQL error but a simple index out of the bounds of the array.
For some reasons, when you try to use a row that is not included in the Rows collection of the datatable you get this error message instead of the less ambiguous IndexOutOfRangeException. This message comes if you pass some value for the index variable that is less than zero or bigger than the number of rows in the datatable dt.
You don't have any check on the number of rows returned by the query and thus is possible that your query doesn't return any record or simple the value of index is -1
void showData(int index)
{
Connection con = new OrderManager.Connection();
SqlDataAdapter sda = new SqlDataAdapter(".......", con.ActiveCon());
dt = new DataTable();
sda.Fill(dt);
// Protect the access to the rows collection of the table...
if(index < dt.RowsCount && index >= 0)
{
TxtBox_OrderID.Text = dt.Rows[index][0].ToString();
// the code that fills the datagrid
}
else
{
// Message for your user about a record not found
}
}
As a side note, please follow ASAP the advice given to parameterize your query. You will avoid Sql Injection and parsin problems
I am getting the error, and not sure how to fix it. When I change the SQL command to another query, it seems to work (with the same amount of data, 10 rows). Ideas? Note: I am aware I should be using parameters in my SQL command, i am just testing.
SqlCommand getLabsCommand = new SqlCommand("SELECT labGrade FROM labStudent WHERE studentID = '"+Label1.Text+"' ");
getLabsCommand.Connection = conn;
ArrayList alMakers = new ArrayList();
conn.Open();
SqlDataReader dr = getLabsCommand.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//alMakers.Add(dr.GetString(1));
alMakers.Add(dr.GetInt32(1));
}
}
string[] labsList = (string[])alMakers.ToArray(typeof(string));
for(int i = 0; i < alMakers.Count; i++)
{
TextBox labs = new TextBox();
labs.ID = "lab" + i;
form1.Controls.Add(labs);
labs.Text = labsList.GetValue(i).ToString();
}
dr.Close();
conn.Close();
}
The function above should be putting these values in each textbox.
25
25
25
25
20
22
25
10
15
16
You are only selecting one column (SELECT labGrade FROM...); indexing is 0-based, so only GetInt32(0) is defined. GetInt32(1) refers to the second column (the first column is index 0, second column is index 1, etc). You probably want:
alMakers.Add(dr.GetInt32(0));
This type of thing is where tools like dapper shine, btw:
var alMakers = conn.Query<int>(
"SELECT labGrade FROM labStudent WHERE studentID = #id",
new { id = Label1.Text }).AsList();
Im wondering how to make my checkboxes in column[3]in dtg_ksluzby checked when the value is in the DB.
klisluz(table where I get the data from) contains columns, id, subkey(which is = vyberradek), text, pocet
This is code for inserting into db.
foreach (DataGridViewRow row in dtg_ksluzby.Rows)
{
if (Convert.ToBoolean(row.Cells[3].Value) == true)
{
SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz(text,pocet,akce,subkey) values(#val1,#val2,#val3,#val4) ", spojeni);
prikaz2.Parameters.AddWithValue("#val1", row.Cells["text"].Value);
prikaz2.Parameters.AddWithValue("#val2", row.Cells["pocet"].Value);
prikaz2.Parameters.AddWithValue("#val3", row.Cells["akce"].Value);
prikaz2.Parameters.AddWithValue("#val4", max + 1);
spojeni.Open();
prikaz2.ExecuteNonQuery();
spojeni.Close();
}
}
Now I would like to check the checkbox when the item is inserted in DB.
Would someone propose me a clue please?
I think I can algorithm this isssue, but I have no idea how can I turn it into the code I thought I can do it somehoe like this :
SqlCommand novyprikaz3 = new SqlCommand("SELECT * FROM klient WHERE ID_K=" + vyberradek, spojeni); //vyberradek selects row ID
spojeni.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{
If text in (row where ID_K=number which comes from vyberradek) is in dtg_ksluzby then check the checkbox in the same row
}
I would like to use this for USER to know which columns did he selected before when he is editing
Thank so much in advance.
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
var row = dtg_ksluzby.Rows[i];
using(var novyprikaz2 = new SqlCommand("SELECT * FROM klient WHERE ID_K=" + vyberradek, spojeni))
{
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.HasRows)
{
row.Cells[3].Value = true;
}
}
}
You have to change vyberradek accordingly to row content.
Try to count it and use ExecuteScalar as below
SqlCommand novyprikaz3 = new SqlCommand("SELECT count(1) FROM klient WHERE ID_K=" + vyberradek, spojeni); //vyberradek selects row ID
spojeni.Open();
Int32 cnt = (Int32) novyprikaz.ExecuteScalar();
If cnt is more than 0 the items exists.
I don't know how to describe what I am looking for but i can illustrate it with diagram which I drawn.
The first below here is 'user input' which will be in gridview and it will require users to input details. the (textbox) is a textbox and the details next to it is an input example.
User Inputs:
Items Quantity Unit Price Total
(textBox)abc (textBox)2 (textBox) 100 (textBox) 200
(textBox)def (textBox)1 (textBox) 150 (textBox) 150
After save button is clicked (I didn't show the button, sorry), the details will be saved in the database such as shown below 'save in database'.
Save in Database:
ID Items Quantity UnitPrice Total
10001 Abc , def 2,1 100,150 200,150
And when the user wants to display the details, the details should show like in the below 'display results'.
Display Results:
ID:10001
Items Quantity Unit Price Total
Abc 2 100 200
def 1 150 150
I hope this explanation is understandable, I am quite poor in explaining and also in ASP.
please help me to code this out in C# or VB because I am out of option to do this.
thank you so much.
code example:
string sql = "INSERT INTO Products(Name, ProductImage, OriginalPrice, DiscountPrice, Descriptions,StockQuantity, Category) VALUES (#Name, #ProdImage, #OriPrice, #DisPrice, #Descrp, #Quantity, #Category)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[7];
param[0] = new SqlParameter("#Name", SqlDbType.VarChar,100);
param[1] = new SqlParameter("#ProdImage", SqlDbType.VarChar, 100);
param[2] = new SqlParameter("#OriPrice", SqlDbType.Float );
param[3] = new SqlParameter("#DisPrice", SqlDbType.Float );
param[4] = new SqlParameter("#Descrp", SqlDbType.VarChar,50);
param[5] = new SqlParameter("#Quantity", SqlDbType.Int);
param[6] = new SqlParameter("#Category", SqlDbType.VarChar,50);
param[0].Value = name;
param[1].Value = image;
param[2].Value = OriPrice;
param[3].Value = disPrice;
param[4].Value = description;
param[5].Value = quantity;
param[6].Value = Category;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
current code:
private string CreateRow(DataTable data, Int32 index, String ColumnName)
{
String[] quan = data.Rows[0][ColumnName].ToString().Split(',');
if (quan.Length >= index)
return quan[index].ToString();
else
return "";
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("");
string sql = "SELECT * FROM SalesOrder WHERE ID = 10010";
DataSet DataFromDataBase = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM SalesOrder WHERE ID = 10010", conn);
adp.Fill(DataFromDataBase);
DataTable TempData = new DataTable();
TempData.Columns.Add("Quantity", typeof(string));
TempData.Columns.Add("UnitPrice", typeof(string));
for (Int32 i = 0; i < 5; i++)
{
DataRow row = TempData.NewRow();
row[0] = CreateRow(DataFromDataBase, i, "Quantity");
row[1] = CreateRow(DataFromDataBase , i, "UnitPrice");
TempData.Rows.Add(row);
}
}
DataFromDataBase is a datatable in which you are getting your data from database.
At last you'll get data in your required format in TempData Datatable.
you have to bind Grisview with TempData Datatable.
I have done this work with only two columns, you can change it according to your columns. I have taken maximum 5 as your maximum number of values in one field. you can modify according to your requirement.
DataTable TempData = new DataTable();
TempData.Columns.Add("Quantity", typeof(string));
TempData.Columns.Add("UnitPrice", typeof(string));
for (Int32 i = 0; i < 5; i++)
{
DataRow row = TempData.NewRow();
row[0] = CreateRow(DataFromDataBase, i, "Quantity");
row[1] = CreateRow(DataFromDataBase, i, "UnitPrice");
TempData.Rows.Add(row);
}
private string CreateRow(DataTable data, Int32 index, String ColumnName)
{
String[] quan = data.Rows[0][ColumnName].ToString().Split(',');
if (quan.Length >= index)
return quan[index].ToString();
else
return "";
}
If you are getting data in DataSet from database. you can pass parameter to CreateRow function as below
CreateRow( DataFromDataBase.Tables[0], i, "UnitPrice");
EDIT like this you have to get data in dataset or datatable (your choice)
DataSet DataFromDataBase = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter("select * from tbdep;select * from tbemployee", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
adp.Fill(DataFromDataBase);
the way you are saving the values is really unrealistic and denormalized.
you should save the values like:
ID Items Quantity UnitPrice Total
10001 Abc 2 100 200
10001 def 1 150 150
and you can use following query in sql:
select * from table where ID = 10001
It will return you two rows in datatable or dataset(whatever you use). you can easily bind it with any control like GridView, Repeater and Datalist.
By this way you can easily reduce you code to display data in your required format.
may it'll help you.
What you are trying to achieve is possible in code, but would require custom concatenation and splitting when reading and writing to storage.
However, I would suggest that you normalize your data and create 2 tables:
IdHeader
HeaderId
CreatedOn
UserName
etc
IdDetail
HeaderId
Item
Quantity
UnitPrice
Total
etc
If you want them under the same ID why not add another column, say OrderId?