捕获用于Mass SMS的DataGridView的一个或多个单元格的ID

时间:2019-10-17 15:14:09

标签: c# sql-server winforms datagridview sms

我在DataGridView中添加了一个CheckBox,以便能够选择多个项目,然后将它们传递给Array,以便能够批量发送消息。

问题1:未被选中。值得一提的是,我所做的就是从DataGridView编辑属性中添加它。

问题2::使用以下字符串块批量发送消息:

string bloque = "";
bloque = bloque + "ID1\t112223333\tMessage\n";

但是,我需要自动发送这些消息。这意味着,除消息或文本外,必须通过选择一个或多个复选框来加载和/或分配 ID PHONE DataGridView 中的“ strong”。为此,请创建以下类:

class Example
    {
        public int id { get; set; }
        public string cellphone{ get; set; }
        public string text{ get; set; }

        public Example() { }
        public Example(int id, string cel, string text) {
            this.id = id;
            this.cellphone= cel;
            this.text= text;
        }

        public string toString() {
            return "ID"+id+"\t" + cellphone+ "\t" + text + "\n";
        }
    }
}

现在,这是当前的界面代码:

public partial class Form1 : Form{
        public Form1(){
            InitializeComponent();
            dtgId.AllowUserToAddRows = false;
        }
        private void Form1_Load(object sender, EventArgs e){
            allId();
            dtgId.ReadOnly = true;
        }

        public void allId(){//method to populate the DataGridView
            try{
                string chain = "chain";
                using (SqlConnection con = new SqlConnection(cadena)){
                    con.Open();
                    string query = "SELECT id FROM clients GROUP BY id";
                    SqlCommand cmd = new SqlCommand(query, con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    dtgId.DataSource = ds.Tables[0];
                    con.Close();
                }
            }
            catch (SqlException ex){
                MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e){//Code to send SMS in bulk
            string user= "user";
            string pass= "pass";
            string respuesta = "";
            int id = Convert.ToInt32(txtId.Text);
            string cellp= txtNumber.Text;
            string text= txtText.Text;
            List<Example> item = new List<Example>();
            Example example= new Example(id, cellp, text);
            item.Add(example);
            string bloque = "";
            //bloque = bloque + "ID1\t1144444444\tMi texto 1\n";
            for (int i = 0; i > item.Count; i++){
                bloque += item[i].toString();
            }

            Uri uri = new Uri("uri");

            HttpWebRequest requestFile = (HttpWebRequest)WebRequest.Create(uri);
            requestFile.Method = "POST";
            requestFile.ContentType = "application/x-www-form-urlencoded";
            StringBuilder postData = new StringBuilder();
            postData.Append("api=" + System.Web.HttpUtility.UrlEncode("1") + "&");
            postData.Append("usuario=" + System.Web.HttpUtility.UrlEncode(user) + "&");
            postData.Append("clave=" + System.Web.HttpUtility.UrlEncode(pass) + "&");
            postData.Append("separadorcampos=" + System.Web.HttpUtility.UrlEncode("tab") + "&");
            postData.Append("bloque=" + System.Web.HttpUtility.UrlEncode(bloque) + "&");

            byte[] byteArray = Encoding.GetEncoding("iso-8859-1").GetBytes(postData.ToString());

            requestFile.ContentLength = byteArray.Length;

            Stream requestStream = requestFile.GetRequestStream();
            requestStream.Write(byteArray, 0, byteArray.Length);
            requestStream.Close();

            HttpWebResponse webResp = requestFile.GetResponse() as HttpWebResponse;

            if (requestFile.HaveResponse){
                if (webResp.StatusCode == HttpStatusCode.OK || webResp.StatusCode == HttpStatusCode.Accepted){
                    StreamReader respReader = new StreamReader(webResp.GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
                    respuesta = respReader.ReadToEnd();
                    MessageBox.Show(respuesta);
                }
            }
        }

        private void dtgId_CellContentClick(object sender, DataGridViewCellEventArgs e){
//With this method, pressing on a checkbox shows the id and the phone in a TextBox
            var row = dtgId.Rows[e.RowIndex];
            var id = Convert.ToInt32(row.Cells["id"].Value.ToString());
            try{
                string conn = "cadena";
                using (SqlConnection con = new SqlConnection(conn)){
                    con.Open();
                    string sql = "SELECT id,cellphone FROM clients WHERE id=@id";
                    SqlCommand cmd = new SqlCommand(sql, con);
                    cmd.Parameters.AddWithValue("@id", id);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read()){
                        txtId.Text = reader["id"].ToString();
                        txtNumero.Text = reader["cellphone"].ToString();
                    }
                }
            }catch (SqlException exc){
                MessageBox.Show("Error: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

总结一下想法:它不发送消息,也就是说,它们尚未到达我。知道我该如何解决吗?

1 个答案:

答案 0 :(得分:0)

我想这样做会更多;通过使用HttpClient发送请求,将手机以及ID加载到网格中,减少了很多低级/冗余代码,因此我们不必再次访问数据库:

public partial class Form1 : Form
{


    HttpClient _httpClient = new HttpClient();

    public Form1()
    {
        InitializeComponent();
        dtgId.AllowUserToAddRows = false;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        AllId();
    }

    public void AllId()
    {//method to populate the DataGridView
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter("SELECT id, cellphone FROM clients GROUP BY id", "constr"))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                dt.Columns.Add("Choose", typeof(bool)); //will become a checkbox column in the grid
                dtgId.DataSource = dt;
            }
        }
        catch (SqlException ex)
        {
            MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private async void SendSms(string id, string number, string message)
    {
        var values = new Dictionary<string, string>
        {
            { "api", "1" },
            { "usario", "user" },
            { "clave", "pass" },
            { "separadorcampos", "tab" },
            { "bloque",  $"{id}\t{number}\t{message}\n" }
        };

        var content = new FormUrlEncodedContent(values);
        var response = await _httpClient.PostAsync("uri", content);
        var responseString = await response.Content.ReadAsStringAsync();

        //do whatever with response...
    }

    private void GoButton_Click(object sender, DataGridViewCellEventArgs e)
    {
        DataTable dt = dtgId.DataSource as DataTable;

        foreach (DataRow ro in dt.Rows) //iterate the table
        {
            if (ro.Field<bool>("Choose")) //if ticked by user
                SendSms(ro.Field<string>("ID"), ro.Field<string>("Cellphone"), "hello, this is my message"); //send the sms
        }

    }
}