C#异常和forloop中的数字 [英] C# Exceptions and number in forloop
问题描述
我显示两个例外情况b
第一个是当我没有把数字放在k中时b $
第二个例外如果K比蛋更多,那么我在Parameters.AddWithValue中得到一个例外。
我想添加一个MessageBox.Show让它添加正确的数字给k
你还将如何添加每行的输出数字。
1 EG216455
2 nEG216456
3 nEG216457
4 nEG216458
6 nEG216459
7 nEG216460
I show two Exceptions
The first one is when I do not put a number in k
The second Exceptions is if K is more then egg I get an exception in the Parameters.AddWithValue
I like to add a MessageBox.Show to have it add the correct number to k
also how would you add to the output numbers for each row.
1 EG216455
2 nEG216456
3 nEG216457
4 nEG216458
6 nEG216459
7 nEG216460
private void button1_Click(object sender, EventArgs e)
{
string egg = textBox1.Text; //egg will show "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460"
int k = Convert.ToInt32(textBox2.Text); // did not put anything in k --- System.FormatException: 'Input string was not in a correct format.'
string[] stringSeparators = new string[];//EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460
string[] s = egg.Split(stringSeparators, StringSplitOptions.None);
DataTable dtSerial = new DataTable();
DataTable table = new DataTable();
for (int i = 0; i < k; i++)
{
//ConfigurationManager.ConnectionStrings["pie"].ConnectionString;
string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1 where ItemCode = @egg", con))//select eggcounter From [Product].[Counter01unit] where eggcounter = @egg
{
cmd.Parameters.AddWithValue("@egg", s[i]); //Exception Unhandled -- System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtSerial.Load(reader);
table = dtSerial.Clone();
foreach (DataRow dr in dtSerial.Rows)
{
table.Rows.Add(dr.ItemArray);
}
}
con.Close();
}
}
dataGridView1.DataSource = dtSerial;
}
推荐答案
我显示两个异常
第一个是当我没有在k中放一个数字时$ b
我想添加一个MessageBox.Show让它添加正确的数字到k $
I show two Exceptions
The first one is when I do not put a number in k
I like to add a MessageBox.Show to have it add the correct number to k
private void button1_Click(object sender, EventArgs e)
{
string egg = textBox1.Text; //egg will show "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460"
int k = Convert.ToInt32(textBox2.Text); // did not put anything in k --- System.FormatException: 'Input string was not in a correct format.'
int k;
bool res = Int32.TryParse(textBox2.Text, out k);
if(!res) // TryParse returned false ...
{
// pop up a message box requesting a valid number, etc.
// ...
return; // leave button click event handler
}
- Wayne
- Wayne
这篇关于C#异常和forloop中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!