当前位置:编程学习 > C#/ASP.NET >>

怎么读取combobox选中的值,并附给一个变量?

如题,小女子万分感谢!!! --------------------编程问答-------------------- 用combobox.selecteditem.text就可以获取控件选中的值了 --------------------编程问答-------------------- string bianlian;  //定义一个string 类型的变量
bianlian=combobox.selecteditem.text ;把下拉列表框中的值读出赋给变量名bianliang --------------------编程问答-------------------- string text=combox.selectvalue.tostring()  或者 combox.text --------------------编程问答--------------------

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
using Sybase.DataWindow;
using System.Data.SqlClient;

namespace Data
{
///
/// Form1 的摘要说明。
///
public class Form1 : System.Windows.Forms.Form
{
 private System.Data.OleDb.OleDbConnection con;
private System.Data.OleDb.OleDbCommand command;

 private System.Data.OleDb.OleDbDataReader reader;

private System.Windows.Forms.ComboBox comboBox1;

private void Form1_Load(object sender, System.EventArgs e)
{
 try
{
con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\pems\data.mdb");//创建数据库联接,这用利用的access数据库
 con.Open();
command=con.CreateCommand();
 command.CommandText="select t_name from teacher";//创建查询语句
 reader=command.ExecuteReader();
while(reader.Read())
 {
 this.comboBox1.Items.AddRange(new object[] {reader["t_name"]});//邦定数据
 }
 reader.Close();
 con.Close();
}
catch(Exception ex)
{
 MessageBox.Show(ex.ToString());
}

}
}

以上是数据绑定的代码示例
获取Combox选中的值并赋值给一个变量
string val = comboBox1.SelectedValue.ToString();即可
--------------------编程问答-------------------- string text=combox.SelectValue.ToString(); --------------------编程问答-------------------- string yourvar=comobox.selectedvalue;

不用再加ToString()了。selectedvalue本身就是string. --------------------编程问答-------------------- --------------------编程问答-------------------- string txt = combobox1.Text; --------------------编程问答-------------------- 看要获取什么值了。
上面说的都基本有了。 --------------------编程问答-------------------- string str; //定义一个string 类型的变量
str=combobox1.selecteditem.text ;//把下拉列表框中的值读出赋给变量名str
这里selecteditem是对于你自己添加的数据来说的。
或者str=combobox1.Text ;//如果下拉列表中的数据是从数据库中读出来的,这样即可,用selecteditem反而有可能出错。
希望对你有帮助! --------------------编程问答-------------------- MessageBox.Show(this.comboBox1.SelectedItem.ToString());
MessageBox.Show(this.comboBox1.Text); --------------------编程问答-------------------- .text 不是object中的属性,是怎么回事?? --------------------编程问答-------------------- 请问这个问题解决了吗?
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,