Solved

Can't see cell values when I don't rebind on postback

Posted on 2011-02-16
2
623 Views
Last Modified: 2012-05-11
I've been stuck on this for a half and day and don't know what is what now...  Here's the issue:
In page load, I loop through a system folder and populate a datatable with the filenames, and a few other text fields.  I then bind that to my Obout Grid control (like the .net Gridview, but pickier).

Then in my aspx page, I had a few template fields to display a textbox and a few check boxes, for each row.  This builds perfectly.  I am unable to get both the template control values and the plain text values in my btnSave_Click event.

When I don't bind my grid on postback, I'm able to see the texbox and checkboxes from my button click event.  But I can't see the filename field that I populated from my initial page_load.  That kind of makes sense.  But when I bind the grid on every post, I can no longer see the values of my textbox or checkboxes.  But I can see the filename field.  
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtFiles = new DataTable();
            DataColumn dc;
            bool isCleanFilename = true;

            // File Name
            dc = new DataColumn();
            dc.DataType = Type.GetType("System.String");
            dc.ColumnName = "Filename";
            dtFiles.Columns.Add(dc);

            // Username
            dc = new DataColumn();
            dc.DataType = Type.GetType("System.String");
            dc.ColumnName = "Username";
            dtFiles.Columns.Add(dc);

            // Status
            dc = new DataColumn();
            dc.DataType = Type.GetType("System.String");
            dc.ColumnName = "Status";
            dtFiles.Columns.Add(dc);

            // Directory
            dc = new DataColumn();
            dc.DataType = Type.GetType("System.String");
            dc.ColumnName = "Directory";
            dtFiles.Columns.Add(dc);

            // Add the row - loop through file list
            DataRow row;


            // Get usernames, compare for existence in Composers folders, then loop through them all, and dump files into DataTable
            string[] roles = new string[] { "SH_COMP", "SH_ADMIN", "SH_SUPER" };

            MembershipUserCollection mc = Membership.GetAllUsers(); //FindUsersByRole(roles);

            foreach (MembershipUser u in mc)
            {
                DirectoryInfo di = new DirectoryInfo("C:\\FTP\\Composers" + "\\" + u.UserName.ToString());

                if (di.Exists)
                {
                    FileInfo[] rgFiles = di.GetFiles("*.wav");
                    foreach (FileInfo fi in rgFiles)
                    {
                        dtFiles.Rows.Add(row);
                    }
                }
            }

            gvTracks.DataSource = dtFiles;
            gvTracks.DataBind();
            }
}



// Button save event which is getting textbox and checkbox, but not Username or Filename

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string strSQL = "", strJob = "", strAction = "INI", Filename = "", Username = "";
        string Notes="", FilenameFormatted = "";
        int RecID = 0;

        //Create sql connection and command
        string cnnString;
        cnnString = ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString;
        SqlConnection cn = new SqlConnection(cnnString);
        SqlCommand cmd = new SqlCommand();

        //Loop through gridview rows to find what Action was checked, then store in metadata and move files
        cn.Open();


        for (int i = 0; i < gvTracks.Rows.Count; i++)
        {
            // Check if Approved
            CheckBox chkApprove = (CheckBox)gvTracks.Rows[i].Cells[4].FindControl("chkApprove");
            if(chkApprove != null && chkApprove.Checked)
            {
                strAction = "Approved";
            }

            // Check if Revise
            CheckBox chkRevise = (CheckBox)gvTracks.Rows[i].Cells[4].FindControl("chkRevise");
            if (chkRevise != null && chkRevise.Checked)
            {
                strAction = "Revise";
            }

            // Check if Denied
            CheckBox chkDeny = (CheckBox)gvTracks.Rows[i].Cells[4].FindControl("chkDeny");
            if (chkDeny != null && chkDeny.Checked)
            {
                strAction = "Denied";
            }

            // Get the Job if any
            DropDownList ddJob = (DropDownList)gvTracks.Rows[i].Cells[5].FindControl("ddJobs");
            if ((ddJob != null) && (ddJob.SelectedItem.ToString() != "...Select Job"))
            {
                strJob = ddJob.SelectedItem.ToString();
                strAction = "Approved";  // Insert into meta just like Approved track, then add to job 
            }

            // Get Filename, Username and Notes
            Filename = gvTracks.Rows[i].Cells[0].Text;
            Username = gvTracks.Rows[i].Cells[2].Text;

Open in new window

0
Comment
Question by:JT_SIRO
2 Comments
 
LVL 10

Accepted Solution

by:
P1ST0LPETE earned 500 total points
Comment Utility
Not exactly sure what is holding you up as you haven't posted enough code for me to determine where the problem is.  Anyway attached below is a working example using a GridView, which you should be able to convert over to your Obout grid control.  I pretty much used your same code except I replaced your file parsing with a method that loads dummy data so I could have something to test with.  Also, I recommend separating out your code into more logical functions. This allows you to more easily focus on one function at a time as well as potentially reducing code as some functionality you'll want to use multiple times in an application.  The below code represents this.

Anyway, copy the code into a new asp.net file, and step through the button click and see the values being populated with data.

Markup:
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvTracks" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="Filename" HeaderText="Filename" />
                <asp:BoundField DataField="Username" HeaderText="Username" />
                <asp:BoundField DataField="Status" HeaderText="Status" />
                <asp:BoundField DataField="Directory" HeaderText="Directory" />
                <asp:TemplateField HeaderText="Approve">
                    <ItemTemplate><asp:CheckBox ID="chkApprove" runat="server" /></ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Notes">
                    <ItemTemplate><asp:TextBox ID="tbNotes" runat="server" /></ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <br />
        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
    </div>
    </form>
</body>
</html>

Open in new window


Code Behind:
 
public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtFiles = FileTable_Create();
            FileTable_Load(dtFiles);          
            gvTracks.DataSource = dtFiles;
            gvTracks.DataBind();
        }
    }

    private void FileTable_Load(DataTable table)
    {
        // Get usernames, compare for existence in Composers folders, then loop through them all, and dump files into DataTable
        string[] files = new string[] { "file1.wav", "file2.wav", "file3.wav", "file4.wav", "file5.wav" };
        string[] names = new string[] { "Paul", "Steve", "Jim", "Rick", "Dave" };
        string[] states = new string[] { "Good", "Bad", "Good", "Bad", "Good" };
        string directory = "C:\\Program Files\\Microsoft";

        for (int i = 0; i < 5; i++)
        {
            table.Rows.Add(DataRow_Create(files[i], names[i], states[i], directory, table));
        }
    }

    private DataRow DataRow_Create(string filename, string username, string status, string directory, DataTable table)
    {
        DataRow row = table.NewRow();
        row["FileName"] = filename;
        row["Username"] = username;
        row["Status"] = status;
        row["Directory"] = directory;
        return row;
    }

    private DataTable FileTable_Create()
    {
        DataTable table = new DataTable("WavFiles");

        // Add 4 column objects to the table:
        DataColumn idColumn = new DataColumn();
        idColumn.DataType = System.Type.GetType("System.Int32");
        idColumn.ColumnName = "ID";
        idColumn.AutoIncrement = true;
        table.Columns.Add(idColumn);

        // File Name
        DataColumn fileColumn = new DataColumn();
        fileColumn.DataType = Type.GetType("System.String");
        fileColumn.ColumnName = "Filename";
        table.Columns.Add(fileColumn);

        // Username
        DataColumn userColumn = new DataColumn();
        userColumn.DataType = Type.GetType("System.String");
        userColumn.ColumnName = "Username";
        table.Columns.Add(userColumn);

        // Status
        DataColumn statusColumn = new DataColumn();
        statusColumn.DataType = Type.GetType("System.String");
        statusColumn.ColumnName = "Status";
        table.Columns.Add(statusColumn);

        // Directory
        DataColumn dirColumn = new DataColumn();
        dirColumn.DataType = Type.GetType("System.String");
        dirColumn.ColumnName = "Directory";
        table.Columns.Add(dirColumn);

        // Create primary key:
        DataColumn[] keys = new DataColumn[1];
        keys[0] = idColumn;
        table.PrimaryKey = keys;

        return table;
    }

    // Button save event which is getting textbox and checkbox, but not Username or Filename
    protected void btnSave_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < gvTracks.Rows.Count; i++)
        {
            string filename = gvTracks.Rows[i].Cells[0].Text;
            string username = gvTracks.Rows[i].Cells[1].Text;
            string status = gvTracks.Rows[i].Cells[2].Text;
            string directory = gvTracks.Rows[i].Cells[3].Text;
            bool approved = ((CheckBox)gvTracks.Rows[i].Cells[4].FindControl("chkApprove")).Checked;
            string notes = ((TextBox)gvTracks.Rows[i].Cells[5].FindControl("tbNotes")).Text;

            //Add data to database here
        }
    }    
}

Open in new window

0
 

Author Comment

by:JT_SIRO
Comment Utility
Thanks for the detailed reply P1.  I appreciate it.  But at first glance, it looks like what I did (forgive the sloppy code - I'm trying to rush this thing out the door).  I'll try to implement it tomorrow though.  I think it's in issue with the Obout grid, either have a bug or that I don't have it configured right.  It has a serialization property that when set to false allows m to see my template control values, but not the datafield elements.  And vise/versa, when serialization="true", I can see the datafield elements but not my template controls...  Uggg.

I've emailed their support, but haven't heard back yet.  If you have any ideas, please let me know, otherwise, I'm going to rip it out and got .net gridview.  I've attached my aspx code with the Obout grid below.
<cc1:Grid ID="gvTracks" runat="server" AutoGenerateColumns="false" Width="100%" Serialize="false" 
                  AllowAddingRecords="false" ShowFooter="true" AllowPageSizeSelection="false" AllowColumnResizing="true" 
                  AllowPaging="false" AllowSorting="true" FolderStyle="../OboutStyles/grid/style_2" 
                  EmbedFilterInSortExpression="true">
        <ScrollingSettings  ScrollHeight="352" />
        <Columns>                        
            <cc1:Column HeaderText="Play" DataField="Filename" HeaderAlign="left" Width="50">
                <TemplateSettings TemplateId="tmpPlayStop"/>
            </cc1:Column>
                      
            <cc1:Column HeaderText="File Name" Width="20%" Wrap="true">
                <TemplateSettings TemplateId="tmpFilename"/>
            </cc1:Column>
            
            <cc1:Column DataField="Username" HeaderText="Username" Width="10%" Wrap="true"></cc1:Column>                           

            <cc1:Column HeaderText="Notes" Width="270">
                <TemplateSettings TemplateId="tmpNotes" />
            </cc1:Column>   

            <cc1:Column HeaderText="Actions" Width="20%">
                <TemplateSettings TemplateId="tmpActions" />
            </cc1:Column>   

            <cc1:Column HeaderText="Submit To Job" Width="19%">
                <TemplateSettings TemplateId="tmpSubmit" />
            </cc1:Column>   

<%--            <cc1:Column HeaderText="Action" Width="28%" Index="4">
                <TemplateSettings TemplateId="tmpAction" />
            </cc1:Column>   --%>
        </Columns>

        <Templates>                        
            <cc1:GridTemplate runat="server" ID="tmpPlayStop">
                <Template>
                    <img id="imgPlay<%# Container.RecordIndex%>" src="../images/musicsearch/play.png" alt="Play" onmousedown="javascript:changeImage('<%# Container.Value.Replace("wav", "mp3")%>','<%# Container.RecordIndex%>', '<%# Convert.ToString(Container.DataItem["TrackTitle"]).Replace("'","987654")%>');" />
                </Template>
            </cc1:GridTemplate>   

            <cc1:GridTemplate runat="server" ID="tmpFilename">
                <Template>
                    <%# Container.DataItem["Filename"] %>
                </Template>
            </cc1:GridTemplate>               

            <cc1:GridTemplate runat="server" ID="tmpActions">
                <Template>  
                        Approve<asp:CheckBox ID="chkApprove" runat="server" />
                        Revise<asp:CheckBox ID="chkRevise" runat="server" />
                        Deny<asp:CheckBox ID="chkDeny" runat="server" />
                </Template>
            </cc1:GridTemplate>   

            <cc1:GridTemplate runat="server" ID="tmpSubmit">
                <Template>  
                    <asp:DropDownList ID="ddJobs" runat="server" DataSourceID="dsJobs" DataTextField="JobName" AppendDataBoundItems="true">
                    <asp:ListItem Selected="True">...Select Job</asp:ListItem>
                    </asp:DropDownList>
                </Template>
            </cc1:GridTemplate>   

            <cc1:GridTemplate runat="server" ID="tmpNotes">
                <Template>  
                    <cc2:OboutTextBox ID="txtNotes" runat="server" Text="" TextMode="multiline" Height="50" Width="260"></cc2:OboutTextBox>
                </Template>
            </cc1:GridTemplate>   
            
        </Templates>                
   </cc1:Grid>

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now