To minimize this code using a loop?
DataGridViewComboBoxColumn combo_1 = new DataGridViewComboBoxColumn();
string name_1 = "name_1";
string name1 = "Name 1";
combo_1.Name = name_1;
combo_1.HeaderText = name1;
DataGridViewComboBoxColumn combo_2 = new DataGridViewComboBoxColumn();
string name_2 = "name_2";
string name2 = "Name 2";
combo_2.Name = nazwa_2;
combo_2.HeaderText = nazwa2;
DataGridViewComboBoxColumn combo_3 = new DataGridViewComboBoxColumn();
string name_3 = "name_3";
string name3 = "Name_3";
combo_3.Name = name_3;
combo_3.HeaderText = name3;
DataGridViewComboBoxColumn combo_4 = new DataGridViewComboBoxColumn();
string nazwa_4 = "name_4";
string nazwa4 = "Name 4";
combo_4.Name = name_4;
combo_4.HeaderText = name4;
Sorry for not clear question, I will try to explain...
I want to add table in to datagridview1
// define combobox column
DataGridViewComboBoxColumn combo_1 = new DataGridViewComboBoxColumn();
string name_1 = "name_1";
string name1 = "Name 1";
combo_1.Name = name_1;
combo_1.HeaderText = name1;
// set value to combobox column
pol.Open();
string list_value = "SELECT value FROM table ORDER BY name ASC";
SqlCommand cmd = new SqlCommand(list_value, conn); //conn is defined above in code
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string name = rdr.GetString(0);
combo_1.Items.Add(name); /
}
pol.Close();
// add all column
dataGridView1.Columns.Add("name_column_1", "Name");
dataGridView1.Columns.Add("name_column_2", "Forname");
int index = 2;
dataGridView1.Columns.Insert(index, combo_1);
//add value to cell
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[index];
cell.Value = dt.Rows[i].ItemArray[index];
For "combo_2", "combo_3" etc. I would have to do a few of these fragments differing only in "_1"
If i can use for loop to add combo_1, combo_2, combo_3
//define combobox
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
for (int i = 1; i <= number_column; i++)
{
string name_1 = "name_" + i;
string name1 = "Name " + i;
combo_1.Name = name_1;
combo_1.HeaderText = name1;
}
//add column
for (int i = 1; i <= liczba_kolumn; i++)
{
int nr = 2;
dataGridView1.Columns.Insert(nr, combo);
nr= nr + 1;
}
//set value
for (int i = 0; i < dt.Rows.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];
dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];
for (int j = 1; j <= number_column; j++)
{
int nr = 2;
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[nr];
cell.Value = dt.Rows[i].ItemArray[nr];
nr = nr + 1;
}
}
error: Additional information: The specified column already belongs to a DataGridView control.
I know why this error is, but i do not know how to change combo name dynamicly.
I'm not sure I understand the question, but I'll take a stab at it...
Let's start with the error you have:
error: Additional information: The specified column already belongs to
a DataGridView control.
I suspect this is because of these 2 lines:
int index = 2;
dataGridView1.Columns.Insert(index, combo);
Do you perhaps mean to use the "i" from your for loop? Or maybe you meant to declare index outside of the for loop (I see you are incrementing it below)?
dataGridView1.Columns.Insert(i, combo);
or
int index = 2;
for (int i = 1; i <= number_of_columns; i++)
{
dataGridView1.Columns.Insert(index, combo);
index = index + 1; // or this could be index++;
}
Now let's look at the title and first line of your question (which is a different topic):
c# dynamic object name
To minimize this code using a loop (or other)?
You could do something like
List<DataGridViewComboBoxColumn> myColumns = new List<DataGridViewComboBoxColumn>();
for(int i=0; i < (the number you want); i++)
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.Name = "name_" + i;
combo.HeaderText = "Name " + i;
}
This would give you a (somewhat) dynamic list of DataGridViewComboBoxColumn. However, if you are just going to add them right away, you may prefer:
for(int i=0; i < (the number you want); i++)
{
dataGridView1.Columns.Insert(i, new DataGridViewComboBoxColumn{
Name = "name_" + i,
HeaderText = "Name " + i});
}
I haven't checked that for syntax, but it should at least be close.
Is that what you were going for?
Thanks PhatWrat, you helped me to solve the problem.
pol.Open();
SqlDataAdapter list_adapter = new SqlDataAdapter("SELECT value FROM box ORDER BY value ASC", pol);
DataTable list_dt = new DataTable();
list_adapter.Fill(list_dt);
string[] items = new string[list_dt.Rows.Count];
for (int i = 0; i < list_dt.Rows.Count; i++)
{
items[i] = list_dt.Rows[i][0].ToString();
//MessageBox.Show(list_dt.Rows[i][0].ToString());
}
pol.Close();
int index = 2;
for (int i = 1; i <= number_of_columns; i++)
{
dataGridView1.Columns.Insert(index, new DataGridViewComboBoxColumn
{
Name = "name_" + i,
HeaderText = "Name " + i,
DataSource = items
});
index = index + 1;
}
pol.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM table ORDER BY name ASC", pol);
DataTable dt = new DataTable();
adapter.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];
dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];
int index_2 = 2;
for (int j = 1; j <= number_of_columns; j++)
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[index_2];
cell.Value = dt.Rows[i].ItemArray[index_2];
index_2 = index_2 + 1;
}
}
pol.Close();
Related
I have populated my data table with random values and formula like =SUM(A1:A2)
when there is 150 columns and 4000 rows in datatable then ReoGrid taking approx 20 minute to be populated.
when i am populating ReoGrid without formula then it takes few second to populate ReoGrid but the moment many SUM formulas are being assigned to cell dynamically then ReoGrid take long time to populated.
Here i am sharing my code. so my request please guys see my code logic and tell me is there any flaw when assigning formula to many cell of ReoGrid.
please tell me how could i simplify the logic to populate grid with formula. Is there way to increase the performance of my code with formula as a result ReoGrid can be populated with in few sec or few minute.
Looking for suggestion and guide line. ReoGrid is free component for winform application https://reogrid.net/.
Here is my code
private void btnBindTable_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string strSum = "", strColName, strImmediateOneUp = "", strImmediateTwoUp = "";
int startsum = 0;
int currow = 0;
bool firstTimeSum = true;
int NumRows = 4000;
int NumColumns = 150;
var sheet = reoGrd.CurrentWorksheet;
sheet.Resize(NumRows, NumColumns); // resize
DataTable dt = new DataTable();
for (int col = 0; col < NumColumns; col++)
{
strColName = GenerateColumnText(col);
DataColumn datacol = new DataColumn(strColName, typeof(string));
dt.Columns.Add(datacol);
}
for (int row = 0; row < NumRows; row++)
{
dt.Rows.Add();
for (int col = 0; col < NumColumns; col++)
{
if (row < 2)
{
dt.Rows[row][col] = new Random().Next(1, NumRows).ToString("D2");
}
else
{
if (firstTimeSum)
{
if (row - currow == 2)
{
currow = row;
startsum = 0;
firstTimeSum = false;
}
else
{
startsum = 1;
}
}
else
{
if (row - currow == 3)
{
currow = row;
startsum = 0;
}
}
if (startsum == 0)
{
strColName = GenerateColumnText(col);
strImmediateOneUp = strColName + ((row + 1) - 1).ToString();
strImmediateTwoUp = strColName + ((row + 1) - 2).ToString();
dt.Rows[row][col] = strSum;
string cellname = GenerateColumnText(col) + (row + 1).ToString();
var cell = sheet.Cells[cellname];
cell.Style.BackColor = Color.LightGoldenrodYellow;
}
else
{
dt.Rows[row][col] = new Random().Next(1, NumRows).ToString("D2");
}
}
}
startsum = 1;
}
sheet["A1"] = dt;
stopwatch.Stop();
TimeSpan timeSpan = stopwatch.Elapsed;
MessageBox.Show(string.Format("Time elapsed: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds));
}
string[] SName = Request.Form.GetValues("Description");
string[] Email = Request.Form.GetValues("Email");
DataTable dtable = dt();
for (int i = 0; i <= SName.Length - 1; i++)
{
DataRow row1 = dtable.NewRow();
row1["Description"] = SName[i];
row1["Email"] = Email[i];
DAL.DMSS insertdata = new DMSS();
insertdata.INSERT_DATA(loggeduser.SUBSIDIARY_CD, input, SName[i], Email[i]);
}
above are my code to get the data from dynamic row add.
if i have 2 rows,data i get is :
now i want to add 1 more data ,sequence number
tried this code but not working..
for (int i = 0; i <= SName.Length - 1; i++)
{
if (i.length <2 )
{
string strvalue = i.PadLeft(2, '0');
}
else
{
string strvalue = i;
}
DataRow row1 = dtable.NewRow();
row1["Description"] = SName[i];
row1["Email"] = Email[i];
DAL.DMSS insertdata = new DMSS();
insertdata.INSERT_DATA(loggeduser.SUBSIDIARY_CD, input, SName[i], Email[i], strvalue);
}
for (int i = 0; i <= SName.Length - 1; i++)
{
var rowNumber = (i + 1).ToString("0#");
}
I have an Excel file with 2 columns [file in my pc]? Now iam getting 2 columns with 8 rows with below code.but continuously i should get 5*2=10 more of same columns with 8 rows in datagridview.
I have written the code which gives result only 2 columns but I should get 10 more columns with 8 rows.below is my code
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dt.Columns.Add((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString());
}
for (int Rnum = 2; Rnum <= 9; Rnum++)
{
dt.Rows.Add((ShtRange.Cells[Rnum, 1] as Excel.Range).Value2.ToString(),
(ShtRange.Cells[Rnum, 1] as Excel.Range).Value2.ToString());
}
}
for (int i = 0; i < 13; i++)
{
DataGridViewTextBoxCell txtbx = new DataGridViewTextBoxCell();
DataGridViewColumn txcol = new DataGridViewColumn();
txcol.CellTemplate = txtbx;
txcol.HeaderText = "column" + i.ToString();
dg1.Columns.Add(txcol);
}
dg1.Rows.Add(8);
int dgRw, dgCol;
dgRw = dgCol = 0;
foreach (DataRow dr in dt.Rows)
{
dg1[dgCol, dgRw].Value = dr[0].ToString();
dgRw++;
if (dgRw == 8)
{
dgCol++;
dgRw = 0;
}
I am getting error :
"There is already an open DataReader associated with this Command
which must be closed first."
Code is as follows :
I am generating dynamic table using 1 table & in every row of that table I want sum calculations from another Table
I have called readDr() first using sqlcommand "cmd" & ExecuteReader(). After that I have called CalTotAmt(string CC) which uses sqlcommand "cmdTotAmt" & ExecuteScalar().
I have used 2 diff sqlcommand still its giving error.
protected void readDr()
{
string str = "select CCNo,TotalAmt,NoOfRect,Energy,New1,Theft,Misc from ChallanTable;";
cmd = new SqlCommand(str, con);
rdr = cmd.ExecuteReader();
}
protected void CreateChallanTable()
{
table.Caption = "Challan Entry";
table.ID = "Challan Entry";
table.BackColor = System.Drawing.Color.Maroon;
table.ForeColor = System.Drawing.Color.Gray;
readDr(); //call to function readDr()
Panel2.Controls.Add(table);
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.BorderStyle = BorderStyle.Ridge;
m = 0;
while (rdr.Read())
{
row = new TableRow();
row.ID = "Row" + m;
row.BorderStyle = BorderStyle.Ridge;
for (n = 0; n <= 6; n++)
{
cell = new TableCell();
cell.ID = "cell" + m + n;
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
//cell.BorderColor = System.Drawing.Color.Azure;
for (n = 0; n <= 0; n++)
{
Label lbl = new Label();
lbl.ID = "lblCCRow" + m + n;
lbl.Text = Convert.ToString(rdr[0]);
lbl.Width = 70;
CCNo = lbl.Text;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 1; n <= 1; n++)
{
Label lbl = new Label();
lbl.ID = "lblTotAmt" + m + n;
lbl.Text = Convert.ToString(rdr[1]);
lbl.Width = 70;
TotAmt = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
Label2.Text = Convert.ToString(CalTotAmt(CCNo));
}
for (n = 2; n <= 2; n++)
{
Label lbl = new Label();
lbl.ID = "lblNoRect" + m + n;
lbl.Text = Convert.ToString(rdr[2]);
lbl.Width = 70;
NoofRects = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 2; n <= 2; n++)
{
Label lbl = new Label();
lbl.ID = "lblEnergy" + m + n;
lbl.Text = Convert.ToString(rdr[3]);
lbl.Width =70;
Energy = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 3; n <= 3; n++)
{
Label lbl = new Label();
lbl.ID = "lblNew" + m + n;
lbl.Text = Convert.ToString(rdr[4]);
lbl.Width =70;
NewSD = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 4; n <= 4; n++)
{
Label lbl = new Label();
lbl.ID = "lblTheft" + m + n;
lbl.Text = Convert.ToString(rdr[5]);
lbl.Width = 70;
Theft = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 5; n <= 5; n++)
{
Label lbl = new Label();
lbl.ID = "lblMisc" + m + n;
lbl.Text = Convert.ToString(rdr[6]);
lbl.Width = 70;
Misc = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
//dr.NextResult();
//outer for-loop end
m++;
}
rdr.Close();
}
protected double CalTotAmt(string CC)
{
double Total = 0;
string str = "select Sum(Amount) from MainDataTable Where CC='" + CC + "' and BU ='" + LogInBU + "'";
SqlCommand cmdTotAmt = new SqlCommand(str,con);
Total = Convert.ToDouble(cmdTotAmt.ExecuteScalar());
Label2.Text = Total.ToString();
return Total;
}
Please help me out.
Here you are trying to open multiple recordset open concurrently on a same connection. You can do that by adding MultipleActiveResultSets=True to the connection string.
Try modifying you code, to make sure DataReader is closed properly:
Sample Code:
protected DataTable readDr()
{
con.Open();
string str = "select CCNo,TotalAmt,NoOfRect,Energy,New1,Theft,Misc from ChallanTable;";
cmd = new SqlCommand(str, con);
rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
rdr.Close();
con.Close();
}
You would generally fix it by writing a single query that computes all of the results in one go - rather than forcing your code to keep querying the database, over and over.
Something like:
select CCNo,TotalAmt,NoOfRect,Energy,New1,Theft,Misc,SumTotal
from ChallanTable ct
cross apply
(select Sum(Amount) as SumTotal from MainDataTable Where CC=ct.CCNo) t
Then you just have to process the results.
(Also, you have a bug in your display code at present - you have two attempts to do something when n==2, the second for will never be entered)
I have a data in data table with say 4 columns.Out of those 10 columns first column contains the date.The data in the table is in the form :
I/p
"15/12/2010",username,24,No
"16/12/2010",username,24,No
"17/12/2010",username,24,No
"18/12/2010",username,24,No
"19/12/2010",username,24,No
"20/12/2010",username,25,No
"21/12/2010",username,24,yes
"22/12/2010",username,24,No
"23/12/2010",username,24,No
"24/12/2010",username,24,No
"25/12/2010",username,24,No
"26/12/2010",Prakhar,24,No
"27/12/2010",username,24,No
"28/12/2010",username,24,No
We have to bind the o/p with the repeater.
For aforemenioned i/p the output should be :
O/P
"15/12/2010 - 20/12/2010",username,24,No
"21/12/2010 - 21/12/2010",username,24,Yes
"22/12/2010 - 25/12/2010",username,24,no
"26/12/2010 - 26/12/2010",username,24,no
"27/12/2010 - 28/12/2010",username,24,no
I.e. we are clubbing all the dates whose corresponsing column values are matching.
We have to write a c# code for it.
First I have created a new Datatable for our final result:
DataTable dtInventoryTable = new dtInventoryTable();
dtInventoryTable.Columns.Add("RateDate", typeof(string));
dtInventoryTable.Columns.Add("RatePlanId", typeof(string));
dtInventoryTable.Columns.Add("RoomTypeId", typeof(string));
private DataTable DisplayInventoryDetails(DataTable dtInventoryDetail)
{
for (int i = 0; i < dtInventoryDetail.Rows.Count; i++)
{
String[] row = new String[dtInventoryDetail.Columns.Count];
String[] row1 = new String[dtInventoryDetail.Columns.Count];
string str=string.Empty;
int h=0;
str = dtInventoryDetail.Rows[i][0].ToString() + " - " +dtInventoryDetail.Rows[i]0].ToString();
for (int j = i+1;j< dtInventoryDetail.Rows.Count; j++)
{
for (int x = 1; x < dtInventoryDetail.Columns.Count; x++)
{
row[x] = dtInventoryDetail.Rows[i][x].ToString();
}
for (int y = 1; y < dtInventoryDetail.Columns.Count; y++)
{
row1[y] = dtInventoryDetail.Rows[j][y].ToString();
}
bool result = ArraysEqual(row, row1);
if (!result)
{
dtInventoryTable = GetRoomRateTable(row, str);
i = j-1;
h = j;
break;
}
else
str= dtInventoryDetail.Rows[i][0].ToString() + " - " + dtInventoryDetail.Rows[j][0].ToString();
h = j;
}
}
if (h >= dtInventoryDetail.Rows.Count-1)
{
dtInventoryTable = GetRoomRateTable(row, str);
break;
}
}
return dtInventoryTable;
}
private DataTable GetRoomRateTable(String[] row,string str)
{
row[0] = str;
dtInventoryTable.LoadDataRow(row, true);
return dtInventoryTable;
}