I want to add the exact value of textbox into datagridview my problem is if i will add another item the last item I add will also change. Here is the print screen of sample problem..
1st try
2nd try
This is my code.
int n = dataGridView3.Rows.Add();
for (int j = 0; j < dataGridView3.RowCount; j++)
{
if (dataGridView3.Rows[j].Cells[1].Value != null && (textBox4.Text == dataGridView3.Rows[j].Cells[4].Value.ToString()))
{
MessageBox.Show("Item Already on List!");
dataGridView3.Rows.Remove(dataGridView3.Rows[n]);
return;
}
else
{
dataGridView3.Rows[j].Cells[1].Value = textBox43.Text;
dataGridView3.Rows[j].Cells[4].Value = textBox4.Text;
dataGridView3.Rows[j].Cells[2].Value = DateTime.Now.ToShortDateString();
dataGridView3.Rows[j].Cells[3].Value = dateTimePicker3.Text;
dataGridView3.FirstDisplayedScrollingRowIndex = n;
dataGridView3.CurrentCell = dataGridView3.Rows[n].Cells[0];
dataGridView3.Rows[n].Selected = true;
}
}
You are looping over the complete array and if it is not yet on the list it goes in to the else part of your if. In that block you assign the current entered values to your row, for every single row you already have.
To fix that I separated the Check for duplicates and the Add part more clearly.
Do notice that if you would have run this through the debugger and stepped on each line of your code (hitting F10 in Visual Studio) you would have spotted this bug easily. Have a look at the blog from Scott Guthrie (among others) http://weblogs.asp.net/scottgu/debugging-tips-with-visual-studio-2010
// check if we already added that one
for (int j = 0; j < dataGridView3.RowCount; j++)
{
if (dataGridView3.Rows[j].Cells[1].Value != null && (textBox4.Text == dataGridView3.Rows[j].Cells[4].Value.ToString()))
{
MessageBox.Show("Item Already on List!");
return;
}
}
// lets add it!
int n = dataGridView3.Rows.Add();
dataGridView3.Rows[n].Cells[1].Value = textBox43.Text;
dataGridView3.Rows[n].Cells[4].Value = textBox4.Text;
dataGridView3.Rows[n].Cells[2].Value = DateTime.Now.ToShortDateString();
dataGridView3.Rows[n].Cells[3].Value = dateTimePicker3.Text;
dataGridView3.FirstDisplayedScrollingRowIndex = n;
dataGridView3.CurrentCell = dataGridView3.Rows[n].Cells[0];
dataGridView3.Rows[n].Selected = true;
Related
I'm still new to using c#. I searched many threads in the forum but couldn't find a solution. I would be grateful if you help.
The problem I can't solve;
If dataGridView2.Rows[i].Cells[5] value=null or empty then run the code below.
If it's full, I want it to increment [i] and move to the next line.
Loop stop point = column length of DataGridView
for (int i = 0; i < **???**; i++)
{
if (**???**)
{
TxtSayKod.Text = dataGridView2.Rows[i].Cells[2].Value.ToString() + dataGridView2.Rows[i].Cells[10].Value.ToString();
TxtHome.Text = dataGridView2.Rows[i].Cells[3].Value.ToString();
TxtAway.Text = dataGridView2.Rows[i].Cells[10].Value.ToString();
button1.PerformClick();
Thread.Sleep(3000);
btnupdate.PerformClick();
}
...
}
You can simplify looping by using a foreach-loop
foreach (DataGridViewRow row in dataGridView2.Rows)
{
if (row.Cells[5].Value is null) // Remove this: ;
{
string away = row.Cells[10].Value.ToString();
TxtSayKod.Text = row.Cells[2].Value.ToString() + away;
TxtHome.Text = row.Cells[3].Value.ToString();
TxtAway.Text = away;
button1.PerformClick();
Thread.Sleep(3000);
btnupdate.PerformClick();
}
}
Even when using a for-statement, you could assign the current row to a variable to simplify the following code:
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
var row = dataGridView2.Rows[i];
if (row.Cells[5].Value is null)
{
string away = row.Cells[10].Value.ToString();
...
}
}
Note that test is int only works if the value has been assigned to the cell as int and not say as number.ToString(). Otherwise, if it was as string, test:
if (row.Cells[3].Value is null or string { Length: 0 })
This uses a type pattern followed by a property pattern. See: Pattern Matching in C# 8.0
The semicolon (;) after your if (**???**) ; (in the unedited question) terminates the if-statement. Remove it to have to following code block to be executed as part of the if.
Do like this, run a loop for all rows and check the respective cell.
foreach (DataGridViewRow row in dataGridView2.Rows)
{
if (row.Cells[5].Value is not null && row.Cells[5].Value.ToString() == string.Empty)
{
}
}
I Inerted a DGV called MarksDGV1 into my application while each cell inside of it has a default value of "0". So, after the user changes the value of some of them, when I try to reach the value for the last edited cell it gives me 0 instead of what the user typed even though it's shown correctly
(Please note: the unselected cells -which doesn't appear in Blue color- show value correctly)
How could I fix that?
Here is my code:
MarksDGV1.Refresh();
MessageBox.Show(MarksDGV1.Rows[0].Cells[1].Value.ToString());
And this is How I built the DGV:
using (DataGridViewTextBoxColumn tmp = new DataGridViewTextBoxColumn())
{
tmp.Width = 90;
tmp.ReadOnly = true;
tmp.HeaderText = "פרק מס.";
MarksDGV1.Columns.Add(tmp);
}
for (int i = 1; i <= 30; i++)
{
using (DataGridViewTextBoxColumn tmp = new DataGridViewTextBoxColumn())
{
tmp.Width = 50;
tmp.HeaderText = "שאלה מס." + i;
MarksDGV1.Columns.Add(tmp);
}
}
for (int i = 0; i < 8; i++)
{
using (DataGridViewRow tmp = (DataGridViewRow)MarksDGV1.Rows[i].Clone())
{
tmp.Cells[0].Value = i + 1;
for (int j = 1; j <= 30; j++)
{
tmp.Cells[j].Value = 0;
//tmp.Cells[j].Value = CurrentExam.Psy[i].Answers[j - 1];
}
MarksDGV1.Rows.Add(tmp);
}
}
Update: I tried typing DataGridView.Refresh(); but didn't work!
Update2: I was able to fix this by selecting another cell -different from the one that I'm concerned in- before I get the values. But that's not a solution for me
From the comments, you are using a button that doesn't take the focus away from the grid, so it remains in edit mode. Try it like this:
MarksDGV1.EndEdit();
MessageBox.Show(MarksDGV1.Rows[0].Cells[1].Value.ToString());
I'm having a slight issue with my program. I'm a first year student and am trying to make a program on flight reservation.
if (txtSeat.Text == "1")
{
btnRowOneSeatOne.BackColor = Color.Red;
goodMessage += "You Selected Row One and Seat One";
}
So, this basically goes down for all 15 seats in the same manner. I have a textbox and if you type numbers from 1-15 the seat will button turn red.
I also did pretty much the same thing in removing the customer. As followed
This was in the remove button handle
if (txtRemove.Text == "1")
{
btnRowOneSeatOne.BackColor = Color.Black;
}
I haven't started on an array yet. Basically for that I have a text box once the number is enter it should store it in the array.
I believe this should be the coding
seatNum = int.Parse(txtSeat.Text);
bool availability = false;
for (int s = 0; s < seats.Length; s++)
{
seats[s] = seatNum
availability = true;
break;
}
if (availability == true)
{
}
I believe this should store the seat in array. I've tried many different ways, but couldn't seem to find away. This is an assignment for a class FYI.
int seatnum = int.Parse(textBox1.Text);
Seat = new int[15];
if (textBox1.Text != "")
{
Seat[seatnum - 1] = seatnum;
}
for (int i = 0; i < 15; i++)
{
if (Seat[i] != 0)
{
listBox1.Items.Add(textBox1.Text);
}
}
I have a function that retrieves a list of device names and stores then in a variable. Then the next step is to get info using 1 device name per line and keep going till the loop is complete.
String text = "";
String errors = "";
for (int i = 0; i < collection.Result.Count; i++)
{
deviceNames += collection.Result[i].DeviceName + Environment.NewLine;
getvirtuals.Location = deviceNames;
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
{
try
{
LtmKey virtualKey = new LtmKey();
virtualKey.Location = virtuals.Result[v].Location;
virtualKey.LocationType = virtuals.Result[v].LocationType;
virtualKey.Key = virtuals.Result[v].Key;
virtualKey.KeyType = LtmKeyType.VirtualAddressPort;
virtualKey.AdminGroup = admingroupComboBox.Text;
var memberStatus = client.GetMemberStatus(virtualKey);
for (int j = 0; j < memberStatus.Result.Count; j++)
{
VirtualMemberStatus status = memberStatus.Result[j];
text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
toolStripProgressBar1.PerformStep();
}
}
catch
{
errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);
}
}
this.allResultsBox.Text = text;
getallstatusButton.Enabled = true;
}
}
The problem that I am running into is that if virtuals is null the tool crashes, instead what I want to do is if virtuals = null I want to move onto the next item from the list. I have tried a if statement but it is not working the way planned, it still comes back as null.
Well this seems like a problem to start with:
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
...
If virtuals.Result is null, how do you expect virtuals.Result.Count to work? I suspect you meant:
if (virtuals.Result != null)
However, I suspect you really just want:
// Keep going with the next iteration of the for loop
if (virtuals == null || virtuals.Results == null)
{
continue;
}
If all you want is to go to the next loop iteration if virtuals is null then you want
if (virtuals == null) continue;
How about just inserting:
if(virtuals == null)
continue;
right after the line
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
Have you tried changing the line:
if (virtuals.Result == null)
to:
if ((virtuals != null) && (virtuals.Result != null))
If this doesn't solve your issue, then you need to indicate what the additional errors are.
if (virtuals.Result == null)
make this
if (virtuals == null)
4th time asking this question after trying to apply so fixes. My problem is I have 2 listboxs one holds IDs and the other holds Cell ids. The ID listbox has 10 items (for testing) and Cell boxes have 5 ID. I'm trying to process listId and listCell at the same time creating update links...
example MakeReq will create txtWebUpdate.Text listID listCell &ire=1, in which is
store.domain.com/101/sec01&ire=1
store.domain.com/102/sec02&ire=1
store.domain.com/103/sec03&ire=1
store.domain.com/104/sec04&ire=1
store.domain.com/105/sec05&ire=1
store.domain.com/106/sec01&ire=1 <- notice how listCell starts over it
continues to loop applying sections until the ListID is complete.
here's the code i've been working with. what's happening with my code is that it's only selecting the first item. It's not going to the next item after its done.
if (listId.Items.Count != 0 && listCell.Items.Count != 0)
{
for (int a = 0; a < listId.Items.Count; a++)
{
for (int b = 0; b < listCell.Items.Count; b++)
{
lblID.Text = listId.Items[a].ToString();
MakeReq(txtWebUpdate.Text + listId.Items[a].ToString() +
"&ire=1", listCell.Items[b].ToString());
//System.Threading.Thread.Sleep(5);
}
}
}
Please only comment if you can help. I'm almost positive that the problem is the for statement and how it's selecting list items, but I may be wrong.
Edit More Info: after testing an example/suggestion for #duffp below the problem is definitely with my For statements. What's happening is its counting that I have 5 entries in ListCell and then output one (the same) ListID 5times but with a different ListCell. Can someone help me write it following what I wrong above?
It may have something to do within the MakeReq method call. I just tried the following code:
private void Form1_Load(object sender, EventArgs e)
{
if (listId.Items.Count != 0 && listCell.Items.Count != 0)
{
for (int a = 0; a < listId.Items.Count; a++)
{
for (int b = 0; b < listCell.Items.Count; b++)
{
lblID.Text = listId.Items[a].ToString();
MakeReq(listId.Items[a].ToString(), listCell.Items[b].ToString());
}
}
}
}
public void MakeReq(string listId, string cellId)
{
Console.WriteLine("store.domain.com/" + listId + "sec01&ire=" + cellId);
}
And it gave the output:
store.domain.com/ID_10sec01&ire=Cell_1
store.domain.com/ID_10sec01&ire=Cell_2
store.domain.com/ID_10sec01&ire=Cell_3
store.domain.com/ID_10sec01&ire=Cell_4
store.domain.com/ID_10sec01&ire=Cell_5
store.domain.com/ID_10sec01&ire=Cell_6
store.domain.com/ID_10sec01&ire=Cell_7
store.domain.com/ID_10sec01&ire=Cell_8
store.domain.com/ID_10sec01&ire=Cell_9
store.domain.com/ID_10sec01&ire=Cell_10
Isn't that what you wanted?
I think there might be some side-effects in MakeReq that you are not showing us. How about adding some debug statements to your code, like this:
if (listId.Items.Count != 0 && listCell.Items.Count != 0)
{
for (int a = 0; a < listId.Items.Count; a++)
{
int listCellCount = listCell.Items.Count;
for (int b = 0; b < listCell.Items.Count; b++)
{
lblID.Text = listId.Items[a].ToString();
MakeReq(txtWebUpdate.Text + listId.Items[a].ToString() +
"&ire=1", listCell.Items[b].ToString());
//System.Threading.Thread.Sleep(5);
Debug.Assert(listCellCount == listCell.Items.Count);
}
}
}
The assertion (listCellCount == listCell.Items.Count) should always be true, unless something is changing listCell.Items.