简体   繁体   中英

Populate Combobox from Database Using the WebService in C# Winforms

Here Is My Code :

[WebMethod]

public SqlDataReader Cmb_BranchMaster() {

        SqlCommand ad1 = new SqlCommand("select * from BranchMaster", conn);
        if (conn.State == ConnectionState.Open)
            conn.Close();

        conn.Open();

        SqlDataReader rdr2 = ad1.ExecuteReader();
        if (rdr2.HasRows)
        {
            while (rdr2.Read())
            {

               // here cmbranchname is my combobox of winforms .. so here in webservice it gievs error 
                cmbBranchName.Items.Add(rdr2[1].ToString());
            }
        }
        conn.Close();
    }

now what to do to return the data and use in my winform

Here is the Solution i Got

Web Service code

static SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["Connection"].ToString());
[WebMethod]
public DataSet Cmb_BranchMaster()
{
    conn.Open();
    SqlCommand ad1 = new SqlCommand("select * from BranchMaster", conn);
    SqlDataAdapter adapt = new SqlDataAdapter(ad1);
    DataSet ds = new DataSet();
    adapt.Fill(ds);
    conn.Close();
    return ds;
}

Winform Code

private void ComboBox_Load(object sender, EventArgs e)
{
    myservice.Service test = new myservice.Service();
    DataSet dd = new DataSet();
    dd = test.Cmb_BranchMaster();
    comboBox1.DataSource = dd.Tables[0];
    comboBox1.DisplayMember = "BranchName";
    comboBox1.ValueMember = "BranchID";
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM