2009-05-05 58 views
0

有一個下拉菜單顯示1-10,用戶從中選擇他想要的文本框的數量 - 如果他選擇無限制,則顯示一個文本框,其中他輸入文本框的確切數量他想。如果他輸入40,則顯示他40個在運行時創建的文本框。從'unlimited'動態控件輸入數據到數據庫

我的問題是,我如何從40-或「他輸入的任何數字」文本框輸入MS SQL數據庫中的數據。我無法動態創建列名,這太乏味乏味和麻煩。有什麼辦法可以做到這一點?

+0

你問,因爲你的老闆正在要求一個下拉菜單 - 你爲什麼要問如何把某些東西放入分貝? – 2009-05-06 03:17:59

+0

我不認爲你有我的問題 – input 2009-05-06 08:39:36

回答

1

你之間是什麼什麼,那就是是頁面和評論或說明或任何一個1對多的關係。你不應該有這樣的模型在你的數據庫text_box_1,text_box_2等相反,它應該是:

CREATE TABLE Some_Entity 
(
    some_entity_id INT NOT NULL, 
    CONSTRAINT PK_Some_Entity PRIMARY KEY CLUSTERED (some_entity_id) 
) 
GO 

CREATE TABLE Some_Entity_Comments 
(
    some_entity_id INT  NOT NULL, 
    comment_number INT  NOT NULL, 
    comments  VARCHAR(1000) NOT NULL, 
    CONSTRAINT PK_Some_Entity_Comments 
     PRIMARY KEY CLUSTERED (some_entity_id, comment_number), 
    CONSTRAINT FK_Some_Entity_Comments_Some_Entity 
     FOREIGN KEY (some_entity_id) REFERENCES Some_Entity (some_entity_id) 
) 
GO 

一旦這樣做了,你可以使用類似於門寫來處理前端的東西代碼。您只需將文本框索引作爲comment_number。

+0

謝謝你和湯姆H.讚賞。 – input 2009-05-06 10:40:59

3

當您創建文本框時,您可以爲它們提供順序標識,然後在回發中遍歷這些文本框,將值寫入數據庫。

例如:

/// <Summary> 
/// This would be fired when the user enters the number of textboxes 
/// the want and click the 'Create Textboxes' button. 
/// </Summary> 
protected void CreateTextBoxes_Click(object sender, EventArgs e) 
{ 
    // Check how many textboxes the user wants 
    int count = Convert.ToInt32(CountTextBox.Text); 

    // Generate the number of textboxes requested 
    // and add them to the page 
    for (int i=0; i < count; i++) 
    { 
     // Create the textbox 
     TextBox textbox = new Textbox(); 

     // Set the ID so we can access it later 
     textbox.ID = "TextBox_" + i; 

     // Add the textbox to the panel 
     TextBoxPanel.Controls.Add(textbox); 
    } 
} 

/// <Summary> 
/// This would be fired when the user has entered values in the textboxes 
/// and clicked the Save button to save the values to the database. 
/// </Summary> 
protected void SaveButton_Click(object sender, EventArgs e) 
{ 
    // Check how many textboxes the user created 
    int count = Convert.ToInt32(CountTextBox.Text); 

    // Loop through them 
    for (int i=0; i < count; i++) 
    { 
     // Get the TextBox 
     TextBox textbox = (TextBox) FindControl("TextBox_" + i); 

     // Get the value 
     string val = textbox.Text; 

     // Insert into DB 
     SaveValueToDatabase(val); 
    } 
] 
1

您是否考慮過將數據存儲爲數據庫中的XML字段?

如果你有40個文本框,你可以只是一個簡單的模式來存儲他們喜歡:

<YourData> 
    <TextBox ID="TextBox1">Value1</TextBox> 
    <TextBox ID="TextBox2">Value2</TextBox> 
    <TextBox ID="TextBox3">Value3</TextBox> 
    ... etc ... 
</YourData> 

無需在你的數據庫的動態領域。您還應該在某處存儲架構。這是存儲可以從記錄更改爲記錄的動態數據的好方法。

0

門,它給我的對象引用的錯誤沒有設置這一行:

// Get the value 
string val = textbox.Text; 

似乎無法找到文本框的控制。