C# 为批量SMS捕获DataGridView的一个或多个单元格的id

C# 为批量SMS捕获DataGridView的一个或多个单元格的id,c#,sql-server,winforms,datagridview,sms,C#,Sql Server,Winforms,Datagridview,Sms,我在DataGridView中添加了一个复选框,以便能够选择多个项目,从而将它们传递给一个数组,以便能够批量发送消息 问题1:未选中按下复选框。值得一提的是,我所做的只是从DataGridView编辑属性中添加它 问题2:要批量发送消息,请使用以下字符串块: string bloque = ""; bloque = bloque + "ID1\t112223333\tMessage\n"; 但是,我需要自动发送这些消息。这意味着,除消息或文本外,必须通过从DataGridView中选择一个或多

我在DataGridView中添加了一个复选框,以便能够选择多个项目,从而将它们传递给一个数组,以便能够批量发送消息

问题1:未选中按下复选框。值得一提的是,我所做的只是从DataGridView编辑属性中添加它

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

string bloque = "";
bloque = bloque + "ID1\t112223333\tMessage\n";
但是,我需要自动发送这些消息。这意味着,除消息或文本外,必须通过从DataGridView中选择一个或多个复选框来加载和/或分配ID电话。为此,请创建以下类:

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:表单{
公共表格1(){
初始化组件();
dtgId.allowUserToAddress=false;
}
私有void Form1\u加载(对象发送方、事件参数e){
allId();
dtgId.ReadOnly=true;
}
public void allId(){//方法来填充DataGridView
试一试{
string chain=“chain”;
使用(SqlConnection con=newsqlconnection(cadena)){
con.Open();
string query=“按id从客户组中选择id”;
SqlCommand cmd=新的SqlCommand(查询,con);
SqlDataAdapter da=新的SqlDataAdapter(cmd);
数据集ds=新数据集();
da.填充(ds);
dtgId.DataSource=ds.Tables[0];
con.Close();
}
}
catch(SqlException-ex){
MessageBox.Show(“错误:+例如消息,“错误”,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
私有无效按钮2\u单击(对象发送者,事件参数e){//代码以批量发送SMS
字符串user=“user”;
字符串pass=“pass”;
字符串respuesta=“”;
intid=Convert.ToInt32(txtId.Text);
字符串cellp=txtNumber.Text;
string text=txtText.text;
列表项=新列表();
示例=新示例(id、cellp、文本);
添加项目(示例);
字符串bloque=“”;
//bloque=bloque+“ID1\t11444444\tMi texto 1\n”;
对于(int i=0;i>item.Count;i++){
bloque+=项[i].toString();
}
Uri=新Uri(“Uri”);
HttpWebRequestFile=(HttpWebRequest)WebRequest.Create(uri);
requestFile.Method=“POST”;
requestFile.ContentType=“application/x-www-form-urlencoded”;
StringBuilder postData=新建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();
Write(byteArray,0,byteArray.Length);
requestStream.Close();
HttpWebResponse webResp=requestFile.GetResponse()作为HttpWebResponse;
if(requestFile.HaveResponse){
如果(webResp.StatusCode==HttpStatusCode.OK | | webResp.StatusCode==HttpStatusCode.Accepted){
StreamReader respReader=新的StreamReader(webResp.GetResponseStream(),Encoding.GetEncoding(“iso-8859-1”);
respuesta=respReader.ReadToEnd();
MessageBox.Show(respuesta);
}
}
}
私有void dtgId_CellContentClick(对象发送方,DataGridViewCellEventArgs e){
//使用此方法,按下复选框可在文本框中显示id和手机
var row=dtgId.Rows[e.RowIndex];
var id=Convert.ToInt32(row.Cells[“id”].Value.ToString());
试一试{
字符串conn=“cadena”;
使用(SqlConnection con=新SqlConnection(conn)){
con.Open();
string sql=“选择id,手机来自id=@id的客户端”;
SqlCommand cmd=新的SqlCommand(sql,con);
cmd.Parameters.AddWithValue(“@id”,id);
SqlDataReader=cmd.ExecuteReader();
if(reader.Read()){
txtId.Text=reader[“id”].ToString();
txtNumero.Text=阅读器[“手机”].ToString();
}
}
}捕获(SqlException exc){
MessageBox.Show(“错误:+exc.Message,“Error”,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}

总结一下想法:它不发送消息,也就是说,它们还没有到达我这里。你知道我该怎么做吗?

我想我会更像这样做;通过使用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
        }

    }
}
公共部分类表单1:表单
{
HttpClient _HttpClient=新的HttpClient();
公共表格1()
{
初始化组件();
dtgId.allowUserToAddress=false;
}
私有void Form1\u加载(对象发送方、事件参数e)
{
AllId();
}
公共无效AllId()
{//方法来填充DataGridView