This tutorial will show you how to set MasterPage file in code-behind. You can remove the MasterPageFile="~/YourMaster.master" from the aspx file it only confused you in the future. Add the PreInit function to your page and set the Master page path. This can be very helpful when you want to set the MasterPage with some logic in the code. It more lines to write but do not let it worry you it always like this when dealing with code behind.
<%@ Page Title="" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
public partial class _Default : System.Web.UI.Page
void Page_PreInit(object sender, EventArgs e)
MasterPageFile = "~/MainMaster.master";
protected void Page_Load(object sender, EventArgs e)