gpt4 book ai didi

c# - 如何拆分逗号分隔值

转载 作者:行者123 更新时间:2023-11-30 22:08:48 25 4
gpt4 key购买 nike

我在 gridview 中有文本框,我正在执行并插入循环遍历 gridview 中每一行的语句。我现在的问题是我可以在文本框中有多个名称,如下所示:

John Carter, Mike David, John Edward,

那么我怎样才能将每个单独的名称拆分并插入到具有相同 ID 的表中呢?例如,如果当前行的 ID =12,那么我的表将如下所示:

ID      Full_Name
12 John Carter
12 Mike David
12 John Edward

这是我的代码:

 foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label ID = row.FindControl("lbl_ID") as Label;
TextBox myUID = row.FindControl("txt_UID") as TextBox;
string Full_Name = Request.Form[row.FindControl("txt_UID").UniqueID];

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);
SqlCommand cmd = new SqlCommand();

cmd.CommandType = CommandType.Text;
cmd.CommandText = @"if not exists(select ID from myTable where ID = @ID)
insert into myTable(ID, Full_Name) values(@ID, @Full_Name)
else update myTable set Full_Name =@Full_Name where ID =@ID";

cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("@Full_Name", SqlDbType.VarChar).Value = Full_Name.ToString();

cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();

}
}

最佳答案

string str = "John Carter, Mike David, John Edward,";
string[] names = str.Split(',');
foreach (string name in names)
{
if (name.Equals(""))
continue;

///dbstuff
///insert into myTable(ID, Full_Name) values(@ID, @name)
///etc, etc
}

强烈假定 ID 不是主键。只要 ID 不是唯一的且不是 key ,这种方法就应该有效。

关于c# - 如何拆分逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22025224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com