[英]Saving data from a data grid view with search functionality to a database
目前,我正在使用WPF和WCF。 WCF處理大部分數據庫端,並且是服務器,而WPF是我正在使用的客戶端。 在WCF端,我有:
public DataSet getAllFixedCostsName(string name)
{
SqlCommand cmd;
if (name == null || name == string.Empty)
{
cmd = new SqlCommand("Select * From FixedCost", con);
}
else
{
cmd = new SqlCommand("Select * From FixedCost Where FixedCostName = " + name, con);
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "FixedCost");
return ds;
}
public void UpdateFixedCosts(DataSet ds)
{
try
{
SqlCommand cmd = new SqlCommand("Select * From FixedCost", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(adap);
adap.Update(ds);
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
在WPF端,我有:
public void SearchFixedCost_OnClick(object sender, RoutedEventArgs e)
{
TextBox search = _contentGrid.Children.OfType<TextBox>().First();
DataGrid dataGrid = _contentGrid.Children.OfType<DataGrid>().First();
ds = new DataSet();
if (_contentGrid.Children.OfType<RadioButton>().First().IsChecked == true)
{
ds = cln.getAllFixedCostsName(search.Text);
}
else if (search.Text.All(char.IsDigit))
{
ds = cln.getAllFixedCostsExpenses(search.Text);
}
else
{
ds = null;
}
if (ds != null)
{
dataGrid.ItemsSource = ds.Tables["FixedCost"].DefaultView;
dataGrid.Columns[0].Visibility = Visibility.Hidden;
}
}
public void UpdateFixedCost_OnClick(object sender, RoutedEventArgs e)
{
cln.UpdateFixedCosts(ds);
}
如果我不搜索任何特定內容,數據將成功更新。 例如,如果我加載程序並單擊“搜索”,它將為該表生成所有行,如果我更新其中一行並保存,則不會崩潰,並且更改將被推送到數據庫。
如果我搜索特定行,請更改該行並保存。 當它到達“ adap.Update(ds,“ FixedCost”)“時,我將在WCF端崩潰,我得到了System.ServiceModel.FaultException。 僅當我對該行或特定數據行進行更改時,才會發生崩潰。
在wcf端的更新方法中,輸入以下代碼:
adap.TableMappings.Add("Table", "FixedCost");
在您的getAllFixedCostsName
方法中,您要告訴它將數據填充到名為“ FixedCost”的表中。 在更新方法中,您創建了一個新的SqlDataAdapter
但是該適配器對“ FixedCost”一無所知。 因此,它正在尋找更新數據庫中名為“ Table”的表的方法。 它找不到它,所以它在抱怨。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.