我想根据列名用数据库中的数据检索(DataSet)替换文本的值,例如:
SQL:
SELECT Fullname, Age FROM User
我有一个文字:
Hello my name is <<Fullname>> and my age is <<Age>>
结果:
Hello my name is Alvin and my age is 18
SQL:
SELECT Lastname, Feeling FROM User
我有一个文字:
Hello my name is <<Lastname>> and I am <<Feeling>>
结果:
Hello my name is Lee and I am Happy
答案 0 :(得分:0)
我最近使用的一个优秀的开源解决方案是dotliquid
请参考这个question详细说明我开始做的事情,并查看Tim的优秀答案
您可以执行查询,构建POCO并使用它来填充模板。您可以从任何地方读取模板文本 - 文件,数据库列,Web服务等。
粗略地了解你如何去做:
public class PersonTemplateInfo : Drop
{
public string Name { get; set; }
public string Feeling { get; set; }
}
然后使用如下:
// Code to read templateText here
Template.NamingConvention = new CSharpNamingConvention();
Template template = Template.Parse(templateText);
// Code to read values
PersonTemplateInfo personTemplateInfo = new PersonTemplateInfo
{
Name = name,
Feeling = feeling
};
string parsedText = template.Render(Hash.FromAnonymousObject(new {personTemplateInfo = personTemplateInfo }));
答案 1 :(得分:0)
据我所知,下面的代码看起来像你需要的。我只是直接在这里输入所以,如果你觉得它有用,你就会明白并纠正它。
SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand(@"SELECT Fullname, Age,Lastname, Feeling,OtherProperties FROM User", connString);
da.Fill(ds, "User");
dt = ds.Tables["User"];
var resultText = "Hello, ";
var textDic = new Dictionary<string,string>(){
{"Fullname","And My name is {0}"},
{"Age","And My age is {0}"},
{"LastName","And my name is {0}"},
{"Felling","And I am {0}"},
{"OtherProperties","And whatever {0}"},
};
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
ColumnName = column.ColumnName;
ColumnData = row[column].ToString();
if(textDic.ContainsKey(ColumnName))
{
resultText+= string.Format(textDic[ColumnName],ColumnData)
}
}
}
// your final result is this resultText