获取选择更改事件的组合框选定值的子串 [英] get substring of selected value of combobox on selection changed event

查看:110
本文介绍了获取选择更改事件的组合框选定值的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string sub1 = (Convert.ToString(dateTimeDate.Value)).Substring(3, 2);
           string sub2 = (Convert.ToString(dateTimeDate.Value)).Substring(8, 2);
           txtRefNo.Text = sub1 + sub2;

             string sub = comboDescription.Text.Trim();

               if (comboDescription.SelectedIndex > -1 || sub != string.Empty)
               {
                   sub = (Convert.ToString(sub)).Substring(0, 3);
                   txtRefNo.Text = txtRefNo.Text + sub;
               }





以上是我在事件上调用的代码



Above is code that i am calling on event

comboDescription_SelectedIndexChanged(object sender, EventArgs e)





我的问题是因为这导致异常



My problem is that this caused exception

Index and length must refer to a location within the string.
Parameter name: length

如何在同一事件中获得所需的值。

how can i get the required value in same event.

推荐答案

你的错误,我猜,发生在以下三行之一:

Your error, I would guess, occurs on one of these three lines:
string sub1 = (Convert.ToString(dateTimeDate.Value)).Substring(3, 2);




string sub2 = (Convert.ToString(dateTimeDate.Value)).Substring(8, 2);






or

sub = (Convert.ToString(sub)).Substring(0, 3);





在尝试任何子字符串函数之前,请检查您要提取的字符串的长度。如果它小于您开始使用的索引或者您尝试提取的索引加X字符,则它将失败。



例如,您可以尝试:







Before you attempt any substring function, check the length of the string you are trying to extract. If it is less than either the index you are starting with or the index plus X characters you are trying to extract then it will fail.

For example you could try:


string sub2 = (Convert.ToString(dateTimeDate.Value));
sub2 = sub2.length > 9 ? sub2.Substring(8, sub2.length > 11 ? 2 : (sub2.length-1)-8) : "";





这样做是检查sub2是否有更长的长度超过9(即它根据你的代码有一个可能的起始索引。然后它看起来可以提取它的长度,可以是1或2个字符。如果它不能提取子字符串,则将sub2设置为等于。



我不是100%的代码,但它只是一个让你合作的概念。



What this would do is check to see if sub2 has a length more than 9 (i.e. it has a possible starting index of 8 as per your code. Then it looks to see what length it can extract, be it 1 or 2 characters. If it cannot extract the sub string it sets sub2 equal to "".

I''m not 100% on the code but its just a concept for you to work with.


这篇关于获取选择更改事件的组合框选定值的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆