2015-01-02 93 views
0

我有2列的表格即IDDETAILS。數據在表就像 id=01 details="pritam=123 sourav=263「像這樣 我在一個Windows應用程序..when工作應用程序將運行輸出來我要告訴..在我的應用程序中一個組合框在那裏。當應用程序將運行所有的id將綁定在表中的組合框2.當用戶將選擇任何id突然細節列數據將以數據網格視圖顯示在這樣的分割格式中。刪除在運行時從網格視圖單個所選行

NAME KEY 
PRITAM 123 
SOURAV 263 

在此數據網格視圖中,用戶可以通過選擇並單擊下面的刪除按鈕來刪除ant行。通過在最後點擊添加新行按鈕插入任何行,修改任何現有的數據,最後點擊更新按鈕,所有的數據將被存儲在該數據庫中,就像以前的格式一樣..爲此我寫了在C#這樣的代碼..

namespace windows_csharpp 
    { 
     public partial class Form5 : Form 
     { 
      SqlConnection cc = new SqlConnection("Integrated Security=true;database=EDIXfer"); 
     SqlDataAdapter da; 
     DataTable dt; 
     public Form5() 
     { 
      InitializeComponent(); 
     } 

     private void Form5_Load(object sender, EventArgs e) 
     { 
      string sql="select EDIScheduleID from ETAProcessSchedule"; 
      da= new SqlDataAdapter(sql, cc); 
      dt = new System.Data.DataTable(); 
      da.Fill(dt); 
      for (int x = 0; x < dt.Rows.Count; x++) 
      { 
       comboBox1.Items.Add(dt.Rows[x][0].ToString()); 
      } 
     } 

     ArrayList ls = new ArrayList(); 
     int ss = 0; 
     int ss1 = 0; 
     int ssp = 1; 

     private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 

      string sql = "select * from ETAProcessSchedule where EDIScheduleID='" + comboBox1.SelectedItem.ToString() + "'"; 
      SqlDataAdapter adp = new SqlDataAdapter(sql, cc); 
      DataTable dt = new System.Data.DataTable(); 

      adp.Fill(dt); 
      string stp = dt.Rows[0][21].ToString(); 
      string[] stp1 = stp.Split(' '); 
      List<Class1> lst = new List<Class1>(); 
      ls.Clear(); 
      for (int x = 0; x < stp1.Length; x++) 
      { 
       ls.Add(stp1[x].ToString()); 
      } 
      for (int x = 0; x < ls.Count; x++) 
      { 
       string ssttt = ls[x].ToString(); 
       string[] sssp = ssttt.Split('='); 


       for (int x1 = 1; x1 < sssp.Length; x1++) 
       { 
        ss = 0; 
        ss1 = ssp; 

        Class1 cs = new Class1() 
        { 
         Value = sssp[ss], Key= sssp[x1].ToString() 
        }; 


         lst.Add(cs); 

       } 

      } 


      dataGridView1.DataSource = lst; 

     } 

     private void Update_Click(object sender, EventArgs e) 
     { 
      string value = null; 
      string keys = null; 
      string query = null; 
      string str = null; 

      for (int i = 0; i < dataGridView1.Rows.Count; i++) 
      { 
       value = dataGridView1.Rows[i].Cells[0].Value.ToString(); 
       keys = dataGridView1.Rows[i].Cells[1].Value.ToString(); 

       string ss = value + '=' + keys; 
       str += ss + ' '; 
      } 
      query = "update ETAProcessSchedule set ProcParameters='"+str+"' where EDIScheduleID='"+comboBox1.SelectedItem.ToString()+"'"; 
      da = new SqlDataAdapter(query, cc); 
      dt = new DataTable(); 
      da.Fill(dt); 
      MessageBox.Show("Data Updated In Database Successfully"); 

     } 

和一個類文件也有..

class Class1 
      { 
      public string Value { get; set; } 
      public string Key { get; set; } 
      } 

好心幫我刪除選定的行,添加新行並更新數據庫中的所有數據像以前的格式一樣..

+1

夥計,失去大寫鎖定。 – Carpetsmoker

+0

爲什麼你不滿意你的接近? – Fabio

回答

0

在你的表單加載綁定數據: -

編輯: -

private void Form5_Load(object sender, EventArgs e) 
    { 
        comboBox1.DataSource = loadddltable(); 
        comboBox1.DisplayMember = "Name"; 
        comboBox1.ValueMember = "ID"; 
    } 

public DataTable loadddl() 
     { 
      OleDbDataReader obj = null; 
      DataTable dt = new DataTable(); 
      try 
      { 
       obj_dbconnection.CommandText = "Select * from TableName"; 
       obj = obj_dbconnection.ExecuteReader(); 
       if (obj != null) 
       { 
        if (obj.HasRows) 
        { 
         dt.Load(obj); 
        } 
       } 

      } 
      catch (Exception) 
      { 

      } 

      finally 
      { 
       if (obj != null) 
       { 
        obj.Close(); 
        obj_dbconnection.Close(); 
       } 
      } 
      return dt; 
     } 

/*Code for Execute Reader*/ 
    public OleDbDataReader ExecuteReader() 
     { 
      OleDbDataReader dr = null; 
      try 
      { 
       Open(); 
       dr = cmd.ExecuteReader(); 
      } 
      catch(Exception) 
      { } 
      return dr; 
     } 

/*Code for binding grid data*/ 

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      dataGridView1.DataSource= getDataForSelectedId(comboBox1.SelectedValue); 
     } 

,然後再插入,修改,刪除按鈕爲模板領域的dataGridView和使用dataGridView1_CellClick事件插入編輯刪除

+0

我假設你的答案是ASP.NET。關於'Winforms'的問題 – Fabio

+0

@Fabio:謝謝你指出我的錯誤。 – Tejas

+0

@Fabio:請檢查答案並在必要時改進答案 – Tejas

1

我想你已經有工作的方法。如果我理解正確的,你只需要兩個功能:
- 負載Schedule細節在DataGridView(每行一個鍵 - 值對)
- 保存編輯/添加/刪除鍵 - 值對數據庫

確保DataGridView組的下一個屬性爲true:

this.YourDataGridView.AllowUserToAddRows = true; 
this.YourDataGridView.AllowUserToDeleteRows = true; 

當然列,並且必須是可編輯

在使用這是在你的表單創建const變量的方法(F ORM1)

private const string DETAILSDELIMITER = ' '; 
private const string NAMEKEYDELIMITER = '='; 

裝載計劃詳細方法在DataGridView

//Use SqlParameters in the query, 
    //if not your application vulnerable for sql injection 
    private void LoadScheduleDetails(string scheduleID) 
    { 
     //You working only with one column, do not use '*' in SELECT statement if not nessesary 
     string query = "SELECT EDIScheduleID, ProcParameters FROM ETAProcessSchedule WHERE EDIScheduleID = @ScheduleID"; 
     DataTable details = new DataTable(); 
     //Get data from database 
     using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString)) 
     { 
      using(SqlCommand detailsCommand = new SqlCommand(query, yourConnection)) 
      { 
       //Adding parameter 
       SqlParameter id = new SqlParameter { ParameterName = "@ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID }; 
       detailsCommand.Parameters.Add(id); 
       using (SqlDataAdapter yourAdapter = new SqlDataAdapter(detailsCommand)) 
       { 
        yourAdapter.Fill(details); 
       } 
      } 
     } 
     this.YourDataGridView.Rows.Clear(); 
     if (details.Rows.Count > 0) 
     { 
      DataRow temp = details.Rows[0]; 
      //get column by name. 
      string[] pairs = temp.Field<String>("ProcParameters").Split(Form1.DETAILSDELIMITER); 
      //Adding rows manually without DataSource 
      foreach(string pair in pairs) 
      { 
       this.YourDataGridView.Rows.Add(pair.Split(Form1.NAMEKEYDELIMITER)); 
      } 
     } 
    } 

方法來保存數據
我覺得更好,如果你在設計師已經創造列
然後,你可以通過它訪問列沒有硬編碼索引的名稱

private void SaveDetails(string scheduleID) 
    { 
     StringBuilder details = new StringBuilder(); 
     foreach(DataGridViewRow dgvr in this.YourDataGridView.Rows) 
     { 
      string name = dgvr.Cells[this.dgvColumn_Name.Name].Value.ToString(); 
      string key = dgvr.Cells[this.dgvColumn_Key.Name].Value.ToString(); 
      //Here you can check if values are ok(not empty or something else) 
      //Create pair 
      details.Append(Form1.DETAILSDELIMITER); 
      details.Append(name); 
      details.Append(Form1.NAMEKEYDELIMITER); 
      details.Append(key); 
     } 
     //remove first space character 
     if (details.Length > 0) 
      details.Remove(0, 1); 
     //Save data to database 
     string query = "UPDATE ETAProcessSchedule SET [email protected] WHERE [email protected]"; 
     using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString)) 
     { 
      using (SqlCommand saveCommand = new SqlCommand(query, yourConnection)) 
      { 
       //Adding parameters 
       SqlParameter id = new SqlParameter { ParameterName = "@ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID }; 
       SqlParameter procParams = new SqlParameter { ParameterName = "@Details", SqlDbType = SqlDbType.NVarChar, Value = details.ToString() }; 
       saveCommand.Parameters.Add(id); 
       saveCommand.Parameters.Add(procParams); 
       saveCommand.ExecuteNonQuery(); 
       MessageBox.Show("Data Updated In Database Successfully"); 
      } 
     } 
    } 

然後使用LoadScheduleDetailscomboBox1_SelectedIndexChanged事件處理

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    string scheduleID = comboBox1.SelectedItem.ToString(); 
    if(String.IsNullOrEmpty(scheduleID) == false) 
    { 
     this.LoadScheduleDetails(scheduleID); 
    } 
} 

加載數據後,用戶可以改變它,添加行,刪除行
當用戶按下「更新」按鈕,然後用SaveDetails方法,
我們從所有行收集數據,用它更新數據庫

private void Update_Click(object sender, EventArgs e) 
{ 
    string scheduleID = comboBox1.SelectedItem.ToString(); 
    if(String.IsNullOrEmpty(scheduleID) == false) 
    { 
     this.SaveDetails(scheduleID); 
    } 
} 
+0

這是正確的答案。+ 1使用鍵值對這就是問題。 – Tejas