I have a database that holds users documents. The Users can store their own meta-data to each document and to accomedate this I have 20 “Key” fields. Each user can use 1 to 20 columns and rename them and order them in the gridview as they please.
The document table looks like this
Documents:
ID int primary key identity,
SiteID int foreign key references sites(id),
PDFFolder varchar(100),
Key1 varchar(300),
keyN varchar(300); //Upto 20 keys
Now I have another table called KeyNames:
KeyNames:
ID int primary key identity,
SiteId int foriegn key references sites(id),
KeyName1 varchar(50),
KeyOrder1 int, //1 is Textbox, 2 is Multi Choice, 3 is date ect
KeyType1 int,
KeyNameN varchar(50), //Repeat 20times
KeyOrderN int,
KeyTypeN int
The Current method I am using is to get a DataTable of the documents for a certain user (who owns a site)
DataTable documents = GetDocuments(int userId, int siteId);
Then I change the Order and the Heading of each Key, If the order < 0 then its removed
//Set Order of Keys
if ((keys.KeyOrder1 <0) || (keys.KeyOrder1 == null))
{
documentsTable.Columns.Remove("Key1");
}
else
{
documentsTable.Columns["Key1"].SetOrdinal((int)keys.KeyOrder1);
documentsTable.Columns["Key1"].ColumnName = keys.Keyname1;
}
//Repeat 20 times
now I simply set the datasource of my gridview to the DataTable and Bind
this.Session["documents"] = documentsTable; //Save to session for future use
gvMail.DataSource = documentsTable;
gvMail.DataBind();
All works well except now I need to make it so the user can edit each Key and save it back to the database. To make things harder, when each row is put in editview I want it to be either a Textbox or DropDownView (in future ill use JavaScript to make a date picker, but not for this example).
I have tried to reverse the process
protected void btnEdit_Click(Object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow row = (GridViewRow)btn.NamingContainer;
if (btn.Text == "Edit")
{
for (int i = 0; i < row.Cells.Count; i++)
{
//Get Header
string header = gvMail.HeaderRow.Cells[i].Text;
//Get Keys
KeyName keys = db.GetKeys(SiteID);
//Cycle through keys to find right key
//ie if (keys.KeyName1 == header)
// {
// switch (keys.KeyType1)
{
case 1: //Add Textbox
case 2: //add drop down box code
// }
}
A couple of the many problem I have is it requires i repeat code 20 times to cycle through all the keys to find which key it is and find the type.
Then the next problem is when I add a control by:
TextBox txtBox = new TextBox();
txtBox.Text = row.Cells[i].Text;
row.Cells[i].Controls.Add(txtBox);
it does not exist after the postback..
Why don’t you use Template Columns in DataGridView to create TextBox and DropDown list columns? It’s very simple and easy and will solve your issue to clearing controls after postback.