Hello every one I am working on my college project I am trying to make an windows application using sql server 2008 and visual c#. I am using grid view for input. Problem is when a new row is added the string does not increment. I mean my empid is at row[i] and cell[0] when i go on to next row the empid is same as in previous row according to my code it should increase by 1 from initial value The result which i want is
row[0]cell[0] = emp6;
row[1]cell[0] = emp7;
row[2]cell[0] = emp8;
row[3]cell[0] = emp9;
and yes i don't want to use row count (digit) as a Id integer because of duplicacy of employeeID in database so to avoid this i am using SQL COUNT to get initial value for ID.
here is my code please help me soon
void emp_id_generator(DataGridView dataGridView1)
{
if (dataGridView1 != null)
{
for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)
{
int j = 6; //this is what i want to increment
Label l = new Label();
l.Text = "EmpID" + (j);
dataGridView1.Rows[count].Cells[0].Value = l.Text;
j=j+1;
}
}
}
Try this way.
J must be initialized outside the loop.
Have a nice day.
void emp_id_generator(DataGridView dataGridView1)
{
if (dataGridView1 != null)
{
int j = 6; //this is what i want to increment
for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)
{
Label l = new Label();
l.Text = "EmpID" + (j);
dataGridView1.Rows[count].Cells[0].Value = l.Text;
j=j+1;
}
}
}
Related
Can someone help me fix this piece of code I found?
It's suppose to shift a whole row up on a winform datagridview.
It works like it's supposed to except for the fact that the old row position stays selected when there is only 1 selected item shifted.
DataGridViewSelectedRowCollection selectedRows = dataGridView.SelectedRows;
dataGridView.ClearSelection(); //this does not work.
for (int i = 0; i <= selectedRows.Count - 1; i++)
{
int selRowIndex = selectedRows[i].Index;
if (selRowIndex > 0)
{
dataGridView.Rows.Remove(selectedRows[i]);
dataGridView.Rows.Insert(selRowIndex - 1, selectedRows[i]);
dataGridView.Rows[selRowIndex - 1].Selected = true;
}
}
Not a fan of what that code you found was trying to do. Try moving selected rows up this way:
for (int i = 1; i < dataGridView.Rows.Count; ++i) {
if(dataGridView.Rows[i].Selected) {
var prevRow = dataGridView.Rows[i - 1];
dataGridView.Rows.RemoveAt(i - 1);
dataGridView.Rows.Insert(i, prevRow);
}
}
Do not call ClearSelection().
To move the selected rows down, try it this way:
for (int i = dataGridView.Rows.Count - 2; i >= 0; --i) {
if (dataGridView.Rows[i].Selected) {
var prevRow = dataGridView.Rows[i + 1];
if (!prevRow.IsNewRow) {
dataGridView.Rows.RemoveAt(i + 1);
dataGridView.Rows.Insert(i, prevRow);
}
}
}
I am relatively new to posting on here but have been stuck on this loop for quite sometime. In the commented section of the code I have successfully written a for loop that does what it is intended to. I have even gone as far as to make sure that I was successfully getting the filtered row count and number of groups from the textbox that the users fills in. However, I need a loop that iterates through the filtered datatable and assigns each row to a group that is set by the user and only if supported based on row count divided by the min number that a team can hold and not exceeding the max number that can be on a team. Finally the results with the added column showing what group the row is in needs to populate another datagridview in this case datagridview2. All of this takes place on a button click. Any help or advice is greatly appreciated. Thanks....
private void btnAssign_Click(object sender, EventArgs e)
{
Random rnd = new Random();
const double maxTeam = 16.00;
const double minTeam = 6.00;
double peopleCnt = 0.00;
int numGroups = Convert.ToInt32(txtNumGroups.Text);
int j = 1;
double totPeopleCnt = Convert.ToDouble(fdt.Rows.Count);
//MessageBox.Show(totPeopleCnt.ToString()+"&"+numGroups.ToString());
//fdt.Columns.Add(new DataColumn("RandomNumber", Type.GetType("System.Int32")));
// for (int i = 0; i < fdt.Rows.Count; i++)
// {
// fdt.Rows[i]["RandomNumber"] = rnd.Next();
// }
// DataView fdv = new DataView(fdt);
// fdv.Sort = "RandomNumber";
// dataGridView2.DataSource = fdv.ToTable();
//fdt.Columns.Add(new DataColumn("RandomNumber", Type.GetType("System.Int32")));
if (totPeopleCnt / minTeam < Convert.ToDouble(numGroups) || totPeopleCnt / maxTeam > Convert.ToDouble(numGroups))
if (totPeopleCnt / minTeam < Convert.ToDouble(numGroups))
{
MessageBox.Show("Number of Players entered will not meet team minimums for " + txtNumGroups.Text + " Teams.");
}
else
{
for (int i = 0; i < totPeopleCnt; i++)
{
peopleCnt++;
fdt.Rows[i][j] = rnd.Next();
j = (j == numGroups ? 1 : j + 1);
}
DataView fdv = new DataView(fdt);
fdv.Sort = numGroups.ToString();
dataGridView2.DataSource = fdv.ToTable();
}
}
I am trying to run an insert statement into a DataTable (I'm doing it this way so that all functions in the statement will be executed so I can get the intended values)
private void insertintoDT(DataTable destination, string InsertStatement)
{
SqlCommand comm = new SqlCommand(InsertStatement);
SqlDataReader reader = new SqlDataReader();
destination.Load(reader);
}
}
This DataTable will then be loaded into a DataGrid so I can see the values that will be inserted. I tried breaking up the insert statement like so:
private void breakupInsert(String insert)
{
DataTable dt = new DataTable();
dgvInsert.Rows.Clear();
string stemp = insert;
int len = stemp.Length;
int itemp = 0;
stemp = stemp.Remove(0, 12);
itemp = stemp.IndexOf("VALUES") - 1;
gvtable = stemp.Substring(0, itemp);
stemp = stemp.Remove(0, itemp + 9);
int itemcount = stemp.Count(x => x == ',') + 1;
string[] values = new string[itemcount - 1];
//populate values
int h = 0;//Used as a start index
int itemc = 0; //item index
for (int k = 0; k < stemp.Length; k++)
{
if (k == stemp.Length - 2)
{
values[itemc] = ExecuteSQL(stemp.Substring(h, (k + 1) - h));
break;
}
else
if (stemp.Substring(k, 2) == (", "))
{
itemp = stemp.IndexOf(", ");
values[itemc] = ExecuteSQL(stemp.Substring(h, k - h));
h = k + 2;
itemc = itemc + 1;
k = k + 1;
}
else if (stemp.Substring(k, 2) == ("),"))
{
itemp = stemp.IndexOf("),");
values[itemc] = ExecuteSQL(stemp.Substring(h, k - h));
h = k + 2;
itemc = itemc + 1;
k = k + 1;
}
else if (stemp.Substring(k, 2) == ("',"))
{
itemp = stemp.IndexOf("',");
values[itemc] = ExecuteSQL(stemp.Substring(h, (k - h) + 1));
h = k + 2;
itemc = itemc + 1;
k = k + 1;
}
}
for (int j = 0; j < values.Length; j++)
{
this.dgvInsert.Rows.Insert(j, j + 1, values[j], values[j].Length);
}
}
However this breaks when a function is in the insert statement ( cast for example)
Is there a way to do it or is this a lost cause?
To Clarify:
I'm essentially trying to provide the user with a text box that they can paste an SQL statement into, this statement will then be reflected in a datagrid. So if an insert statement is put in, the datatable will reflect the values that are being inserted. But without ever inserting them into the database.
Queries are database-specific, so parsing queries is done by a database-specific component, probably on the database server and otherwise the ADO.NET driver for that database.
You could use SQLite to create an in-memory database, so your end users won't have to set up a separate database (it does require SQLite dll's shipped with your application), however using that approach forces you to use the SQLite dialect, and some queries might not work if you attempt to use them on a different database. It does sound to me like the easiest way out though.
This answer suggests using the entity framework to parse queries, but I don't know if it can help you update the datatable. I haven't tried this myself but it might be worth looking into.
I am creating a calculator where the user enters a number into a textbox specifing how many inputs (textboxes) the user wants to have (Code not shown). I have used a textbox array to create these textboxes. The problem comes when I want to get the text from these textboxes to perform the calculations, the code I have written so far for this is shown below:
int n;
TextBox[] textBoxes;
Label[] labels;
double[] values;
public void GetValue()
{
n = Convert.ToInt16(txtInputFields.Text);
values = new double[n];
textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
}
}
I am unsure what to put in the for loop for this; I have tried the following:
values[n] = Convert.toDouble(textBoxes[n].Text);
but it gives me the error: Index was outside the bounds of the array.
I am new to C# and programming in general so any help would be much appreciated.
Thanks.
EDIT: Code to create textboxes is shown here:
public void InstantiateTextFields()
{
n = Convert.ToInt16(txtInputFields.Text);
int posLeft = 100;
textBoxes = new TextBox[n];
labels = new Label[n];
// Creates number of inputs and labels as specified in txtInputFields (n).
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
textBoxes[i].Top = 100 + (i * 30);
textBoxes[i].Left = posLeft;
textBoxes[i].Name = "txtInput" + (i + 1);
labels[i] = new Label();
labels[i].Top = 100 + (i * 30);
labels[i].Left = posLeft - 50;
labels[i].Text = "Input " + (i + 1);
labels[i].Name = "lblInput" + (i + 1);
}
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
Your code in the GetValue method recreates the array of textboxes and doing so destroys the orginal content (the textboxes dynamically created InstantiateTextFields).
In this way your loop fails with Object Reference not set.
You just need to use the global variable without reinitiaizing it
public void GetValue()
{
n = Convert.ToInt16(txtInputFields.Text);
values = new double[n];
// textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
values[i] = Convert.ToDouble(textBoxes[i].Text);
}
}
There is something to be said about reading the input text and converting it to double without checks. If your user types something that cannot be converted to a double your code will crash on the Convert.ToDouble line. Use instead
double temp;
for (int i = 0; i < n; i++)
{
if(double.TryParse(textBoxes[i].Text, out temp)
values[i] = temp;
else
{
// Not a double value....
// A message to your user ?
// fill the array with 0 ?
// Your choice....
}
}
values[n] = Convert.toDouble(textBoxes[n].Text); gives you error because n is outside of the array. You allocate an array with the size of n which is zero indexed aka the last element is at position n-1.
for (int i = 0; i < n; i++)
{
values[i] = Convert.toDouble(textBoxes[i].Text);
}
I'm trying to automate a web application. What i'm trying to do is login to a website, select a dropdown and insert some Id into textbox and then click on a button and finally reading some text.
All is well when this is done for a single Id. Now I have a datatable containing say 100 rows. I want to loop and change the texbox value, click on the button and read new text.
Can this be achieved with web browser control? I shall post my test code tomorrow...
Any approach in right direction is highly appreciated. Thank a ton in advance.
if (this.wbProject1.ReadyState == WebBrowserReadyState.Complete)
{
mFrameCount += 1;
wbProject1.Document.Window.Frames[1].Document.GetElementsByTagName("select")[0].SetAttribute("Value", "1");
HtmlWindow win = wbProject1.Document.Window;
if (win.Frames.Count > mFrameCount && win.Frames.Count > 0) done = false;
for (int rowCount = dtCertificateNo.Rows.Count - 1; rowCount >= 0; rowCount--)
{
int loopCount = 0;
DataRow drow = dtCertificateNo.Rows[rowCount];
wbProject1.Document.Window.Frames[1].Document.GetElementsByTagName("input")[1].SetAttribute("value", drow["CertificateNo"].ToString().Trim());
wbProject1.Document.Window.Frames[1].Document.GetElementsByTagName("a")[4].InvokeMember("click");
System.Threading.Thread.Sleep(2000);
if (done)
{
string[] str2 = wbProject1.Document.Window.Frames[1].Document.Body.InnerText.Replace("\r\n", "").Split(' ');
string[] str3 = wbProject1.Document.Window.Frames[1].Document.Body.InnerText.Replace("\r\n", "|").Split('|');
for (int i = 0; i < str2.Length - 1; i++)
{
if (str2[i] == "Status:")
{
if (str2[i + 1] == "Unperfected")
{
for (int j = 0; j < str3.Length - 1; j++)
{
if (str3[j].Contains("Reason:"))
{
DataRow drowFirst = dtReasons.NewRow();
drowFirst["CertificateNo"] = drow["ID"].ToString();
drowFirst["Reason"] = str3[j];
drowFirst["Comment"] = str3[j + 1];
dtReasons.Rows.Add(drowFirst);
// Here document inner text does not refreshes and remains the same for all the id's (holds the last one).
}
}
}
}
}
drow.Delete();
dtCertificateNo.AcceptChanges();
}
}
if (done)
{
ExcelExport(dtReasons, "D:\\Test");
this.Close();
}
}
else
{
Application.DoEvents();
}