如何根据C#中的数字上下值从文本框中删除字符?
我有两个字段: 加载-默认值为4 我的目标是根据选择的数字铸造产品代码文本框 示例 根据上面的示例,这应该是输出: 如果我将其设置为2,则应为: 我尝试过的:如何根据C#中的数字上下值从文本框中删除字符?,c#,C#,我有两个字段: 加载-默认值为4 我的目标是根据选择的数字铸造产品代码文本框 示例 根据上面的示例,这应该是输出: 如果我将其设置为2,则应为: 我尝试过的: private void numericUpDown1_ValueChanged(object sender, EventArgs e) { productCode.Text = (productCode.Text.Substring(0, productCode.Text.Length - numericUpDown1.V
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
productCode.Text = (productCode.Text.Substring(0, productCode.Text.Length - numericUpDown1.Value));
}
错误
Cannot convert from decimal to int
还有…
我已经对此进行了测试:
productCode.Text = (productCode.Text.Substring(0, productCode.Text.Length - 4));
如果我多次应用它,就会出错:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Length cannot be less than zero.
问题
实现这一目标的正确方法是什么?看看你的例子,我认为这是一种方法:
private string originalProductCode = "0001050OL"; //Set this if productcode changes
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
productCode.Text = (originalProductCode.Substring(0, (int)numericUpDown1.Value));
}
看看你的例子,我认为这是一种方法:
private string originalProductCode = "0001050OL"; //Set this if productcode changes
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
productCode.Text = (originalProductCode.Substring(0, (int)numericUpDown1.Value));
}
转换为整数…->
productCode.Text=(productCode.Text.Substring(0,productCode.Text.Length-(int)numericUpDown1.Value))代码>。此外,如果使用Substring
作为ex-当文本为空或没有要减去的长度时,您应该编写代码来处理ArgumentOutOfRangeException。将numericUpDown1\u ValueChanged
事件中的代码替换为var s=productCode.text.TrimStart('0');productCode.Text=s.PadLeft((int)numericUpDown1.Value+s.Length,'0')代码>啊,对不起,我以为你需要前导零。让我检查一下。@dr.null我第二天早上回来上班时会试一试:D@dr.null喂,不行,不行。我会找到另一个选择。强制转换为int…->productCode.Text=(productCode.Text.Substring(0,productCode.Text.Length-(int)numericUpDown1.Value))代码>。此外,如果使用Substring
作为ex-当文本为空或没有要减去的长度时,您应该编写代码来处理ArgumentOutOfRangeException。将numericUpDown1\u ValueChanged
事件中的代码替换为var s=productCode.text.TrimStart('0');productCode.Text=s.PadLeft((int)numericUpDown1.Value+s.Length,'0')代码>啊,对不起,我以为你需要前导零。让我检查一下。@dr.null我第二天早上回来上班时会试一试:D@dr.null喂,不行,不行。我会找到一个替代方案。原始产品代码将取决于用户输入。它不会一直保持为0001050OL
我可以键入这样的内容作为示例:Hello World代码>。从那里,数字的上下将决定要删除多少字符。@LV98我为您提供了解决问题的最少代码。您应该能够了解如何使用其他方法更改originalProductCode变量。例如,这可能是一个私有的void productCode_TextChanged(objectsender,EventArgs e){}。原始产品代码将取决于用户输入。它不会一直保持为0001050OL
我可以键入这样的内容作为示例:Hello World代码>。从那里,数字的上下将决定要删除多少字符。@LV98我为您提供了解决问题的最少代码。您应该能够了解如何使用其他方法更改originalProductCode变量。例如,这可能是一个私有的void productCode_TextChanged(对象发送方,EventArgs e){}。