我有一個ListView。它有6列:c#ListView數據庫保存問題
question_id | question_text | start_time | end_time | status | repeat
分別。現在我可以顯示數據庫中的數據。這是我的代碼:
private void Voting_Editor_Tool_Load(object sender, EventArgs e)
{
GetData();
}
public void GetData()
{
try
{
now = DateTime.Now;
String time_date = now.ToString();
myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
//myConnection.Open();
//SqlDataReader dr = new SqlCommand("SELECT question_text,question_id FROM otvtbl_question ", myConnection).ExecuteReader();
// listView1.Columns.Clear();
listView1.Items.Clear();
myConnection.Open();
String MyString1 = string.Format("SELECT question_id,question_text,start_time,end_time,status,repeat FROM otvtbl_question");
com = myConnection.CreateCommand();
com.CommandText = MyString1;
dr = com.ExecuteReader();
ListViewItem itmX;
//Adding the Items To The Each Column
while (dr.Read())
{
itmX = new ListViewItem();
itmX.Text = dr.GetValue(0).ToString();
var word = itmX.Text;
for (int i = 1; i < 6; i++)
{
itmX.SubItems.Add(dr.GetValue(i).ToString());
}
if (dr.GetDateTime(2) < now && dr.GetDateTime(3) > now)
{
itmX.SubItems[4].Text = "Broadcasting";
}
else if (dr.GetDateTime(3) < now)
{
string a=Convert.toString(dr.GetDateTime(3));
itmX.SubItems[4].Text = "Expired";
String broadcast = string.Format("UPDATE otvtbl_question SET status='EXPIRED' where start_time='{6}'",a);
//Execute the SqlCommand
com = new SqlCommand(broadcast, myConnection);
com.ExecuteNonQuery();
}
else
{
itmX.SubItems[4].Text = "Not Expired";
}
listView1.Items.Add(itmX);
}
dr.Close();
myConnection.Close();
}
catch (Exception ex)
{
//Error Message While Fetching
MessageBox.Show("Error While Fetching the data From the DataBase" + ex);
}
finally
{
//Closing The Connection
if (dr != null)
dr.Close();
if (myConnection.State == ConnectionState.Open)
myConnection.Close();
}
}
在此代碼中,狀態列必須在用戶每次加載表單時更新。在窗體加載時,它必須檢查start_time是否大於當前時間。如果它大於狀態欄必須顯示NOT EXPIRED
,否則它必須顯示EXPIRED
。問題是我可以通過比較時間來顯示Status
列中的EXPIRED
和NOT EXPIRED
列,但我想將EXPIRED
和NOT EXPIRED
值保存在數據庫中,同時顯示狀態列中的值。我曾嘗試使用以下命令來更新它:
String broadcast = string.Format("UPDATE otvtbl_question SET status='EXPIRED' where start_time='{6}'",a);
//Execute the SqlCommand
com = new SqlCommand(broadcast, myConnection);
com.ExecuteNonQuery();
但它說:
的DataReader已到更新數據之前被關閉。
我甚至試圖關閉DataReader和嘗試更新和它說不同的錯誤爲:
索引(從零開始)必須大於該參數的大小大於或等於零且小於列表
有什麼建議嗎?
不應該將您的更新查詢作爲參數字段{0}而不是{6}嗎? – ChristiaanV 2011-05-27 06:16:02