获取用于群发短信的 DataGridView 的一个或多个单元格的 ID
Capture the id of one or more cells of a DataGridView for Mass SMS
我向 DataGridView 添加了一个 CheckBox,以便能够 select 多个项目,然后将它们传递给一个数组,以便能够批量发送消息。
问题 1: 按下 CheckBox 未选中。值得一提的是,我所做的只是从 DataGridView 编辑属性中添加它。
问题 2: 要批量发送消息,请在字符串中使用以下块:
string bloque = "";
bloque = bloque + "ID1\t112223333\tMessage\n";
但是,我需要自动发送这些消息。这意味着,除了消息或文本之外,ID 和 PHONE 必须由select从 DataGridView 中获取一个或多个 CheckBoxes。为此,创建以下 class:
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);
}
}
}
}
总结一下这个想法:它不发送消息,也就是说,它们还没有到达我这里。知道我该如何解决吗?
我想我会更像这样;通过使用 HttpClient 发送请求,通过将手机和 ID 加载到网格中,减少了很多低 level/redundant 代码,这样我们就不必再次访问数据库了:
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
}
}
}
我向 DataGridView 添加了一个 CheckBox,以便能够 select 多个项目,然后将它们传递给一个数组,以便能够批量发送消息。
问题 1: 按下 CheckBox 未选中。值得一提的是,我所做的只是从 DataGridView 编辑属性中添加它。
问题 2: 要批量发送消息,请在字符串中使用以下块:
string bloque = "";
bloque = bloque + "ID1\t112223333\tMessage\n";
但是,我需要自动发送这些消息。这意味着,除了消息或文本之外,ID 和 PHONE 必须由select从 DataGridView 中获取一个或多个 CheckBoxes。为此,创建以下 class:
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);
}
}
}
}
总结一下这个想法:它不发送消息,也就是说,它们还没有到达我这里。知道我该如何解决吗?
我想我会更像这样;通过使用 HttpClient 发送请求,通过将手机和 ID 加载到网格中,减少了很多低 level/redundant 代码,这样我们就不必再次访问数据库了:
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
}
}
}