Here I am trying to load the dropdownlist box from a column of a table in Mysql(which contains repeated values), so I need to get unrepeated values.
This is my code:
MySqlConnection cn = new MySqlConnection("Connection String");
MysqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
cmd = cn.createcommand();
cmd.CommandText = "Select Columnname from tablename";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DropDownList.Items.Add(reader.GetString("Columnname"));
}
}
cn.close();
}
尝试编辑SQL查询以获取DISTINCT
结果
cmd.CommandText = "SELECT DISTINCT Columnname FROM tablename";
The code snippet is then presumably called more than once, maybe on each post back. Just clear the items first:
DropDownList.Items.Clear();
One thing to note is that when ViewState
is enabled there is no need to reload your drop down lists on each subsequent post back. That also means that you can decide rather to execute this code only if if (!this.IsPostBack
)`.
table1:
id name
1 saravanan
2 karumbasalam G
3 saravanan
select distinct name from table1
output:
name
saravanan
karumbasalam G
Use the distinct
keyword used to avoid duplicates
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.